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",
}
CodePudding user response:
Use: unset($array['key'])
here $array is your array and the key is type in your scenario
CodePudding user response:
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