如何循环遍历多维数组并在PHP中以递归方式删除键?

时间:2014-02-27 21:52:52

标签: php arrays multidimensional-array foreach

我正在尝试遍历多维文档,代码发布在下面。我想要一个可以传递数组的函数和一个我可以删除的键。它就像函数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] =>    
                )   
        )
)                       


我想删除ID并返回一个除了ID之外的所有内容的新数组。

1 个答案:

答案 0 :(得分:5)

你有一个对象数组

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');