-2

How do I remove elements from an array of objects? I already know the name of the keys to be removed (in the example below: type).

For example, this is the array I have:

  {
    "color": "purple",
    "type": "minivan",
  },
  {
    "color": "red",
    "type": "station wagon",
  }

And this is the array I would like to get:

  {
    "color": "purple",
  },
  {
    "color": "red",
  }
  • You can loop through the array and use ```unset($obj->type)```, see https://www.php.net/manual/en/function.unset.php – Jordy Apr 08 '22 at 11:42
  • Does this answer your question? [PHP: How to remove specific element from an array?](https://stackoverflow.com/questions/2448964/php-how-to-remove-specific-element-from-an-array) – nicael Apr 08 '22 at 11:53

2 Answers2

0

Use: unset($array['key'])

here $array is your array and the key is type in your scenario

0

Like @Jordy suggested you can use unset().

If you wish to remove all the 'type' from each object, you can use a foreach loop:

$cars = array (
  array("name"=>"Volvo","color"=>"purple", "type"=>"minivan"),
  array("name"=>"BMW","color"=>"red", "type"=>"station wagon")
);
    
function printCars($cars){
    foreach($cars as $key => $val){
        foreach( $val as $keyItem => $valKey){
            echo $keyItem ." : ".$valKey."</br>";
        }
    }
}
  • prints

     name: Volvo 
     color : purple 
     type : minivan 
     name : BMW 
     color : red
     type : station wagon
    

Then to remove your 'type' key:

foreach($cars as $key => $val){
    foreach( $val as $keyItem => $valKey){
        if($keyItem = "type"){        
            unset($cars[$key][$keyItem]);
        }
    }
}
printCars($cars);
  • prints

     name: Volvo 
     color : purple 
     name : BMW 
     color : red
    
Elladee
  • 11
  • 1