Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you loop through an multidimenional array and delete key by name recursively in PHP?

I am trying to loop through an multidimensional arrary and the code is posted below. I want a function that I could pass the array to and a key that I could remove. It would be something like function removeItemFromMArray($YourArray, $RemoveKeyNamed); .


stdClass Object
(
    [products] => Array
        (
            [0] => stdClass Object
                (
                    [title] => New Balance - Variable Demo
                    [id] => 10393
                    [created_at] => 2013-07-24T14:35:21Z
                    [updated_at] => 2013-07-24T14:35:21Z
                    [type] => variable
                    [status] => publish
                    [downloadable] => 
                    [virtual] => 
                )


            [1] => stdClass Object
                (
                    [title] => Mismo - Briefcase
                    [id] => 9619
                    [created_at] => 2013-06-10T13:18:17Z
                    [updated_at] => 2013-06-10T13:18:17Z
                    [type] => simple
                    [status] => publish
                    [downloadable] => 
                    [virtual] =>    
                )   
        )
)                       


I want to remove ID and return a new array with everything except for the ID.

like image 375
Alex Williams Avatar asked Feb 27 '14 21:02

Alex Williams


1 Answers

You have an array of objects

function removeItemFromMArray($YourArray, $RemoveKeyNamed) {
    foreach ($YourArray as $object) {
        unset($object->$RemoveKeyNamed);
    }
    return $YourArray;
}
$products = removeItemFromMArray($myArray->products, 'id');

OR

function removeItemFromMArray(&$YourArray, $RemoveKeyNamed) {
    foreach ($YourArray as $object) {
        unset($object->$RemoveKeyNamed);
    }
}
removeItemFromMArray($myArray->products, 'id');
like image 163
cornelb Avatar answered Sep 21 '22 17:09

cornelb