Delete element from multi-dimensional array based on key
How can I delete an element from a multi-dimensional array given a key?
I am hoping for this to be greedy so that it deletes all elements in an array that match the keys I pass in. I开发者_Python百科 have this so far where I can traverse a multi-dimensional array but I can't unset the key I need to because I don't have a reference to it!
function traverseArray($array, $keys)
{
foreach($array as $key=>$value)
{
if(is_array($value))
{
traverseArray($value);
} else {
if(in_array($key, $keys))
{
//unset(what goes here?)
}
}
}
}
The following code works (and doesn't use deprecated stuff), just tested it:
function traverseArray(&$array, $keys) {
foreach ($array as $key => &$value) {
if (is_array($value)) {
traverseArray($value, $keys);
} else {
if (in_array($key, $keys)){
unset($array[$key]);
}
}
}
}
You could use pass by reference, declare your function like this:
function traverseArray(&$array, $keys)
{
foreach($array as $key=>$value)
{
if(is_array($value))
{
traverseArray($value, $keys);
}else{
if(in_array($key, $keys)){
unset($array[$key]);
}
}
}
}
then you can unset the key and it will vanish from the original passed value too since the $array
in the function is merely a pointer to the array you passed so it updates that array.
unset($array[$key]);
For more information check the php documentation on passing by reference
You can do this
unset($array[$key]);
because $array
will not be a copy of the original array, just a reference to it, so any modifications will hold.
Also, you have a small bug in your snippet: when you make the recursive call, you forget the pass the $keys
parameter.
and don't forget to modify foreach:
foreach($array as $key=>&$value)
精彩评论