我正在尝试创建一个函数来从动态多维数组中删除键,我需要给出:
removeByIndex(['hello', 'my', 'world']);
然后该函数需要执行以下操作:
unset($array['hello']['my']['world']);
索引的数量是动态的,例如:
removeByIndex(['hello', 'my']); // Do: unset($array['hello']['my']);
removeByIndex(['hello']); // Do: unset($array['hello']);
我尝试使用一些foreach
循环,但我还没有找到解决方案。
欢迎任何帮助。
最佳答案
不需要eval()
,只需一点点引用。
/**
* Remove index from multi-dimensional array.
*
* @param array $array
* The array to remove the index from.
* @param array $indices
* Indexed array containing the indices chain up to the index that should be
* removed.
* @return
* The array with the index removed.
* @throws \InvalidArgumentException
* If the index does not exist within the array.
*/
function removeByIndex(array $array, array $indices) {
// Create a reference to the original array.
$a =& $array;
// Count all passed indices, remove one because arrays are zero based.
$c = count($indices) - 1;
// Iterate over all passed indices.
for ($i = 0; $i <= $c; ++$i) {
// Make sure the index to go down for deletion actually exists.
if (array_key_exists($indices[$i], $a)) {
// This is the target if we reached the last index that was passed.
if ($i === $c) {
unset($a[$indices[$i]]);
}
// Make sure we have an array to go further down.
elseif (is_array($a[$indices[$i]])) {
$a =& $a[$indices[$i]];
}
// Index does not exist since there is no array to go down any further.
else {
throw new \InvalidArgumentException("{$indices[$i]} does not exist.");
}
}
// Index does not exist, error.
else {
throw new \InvalidArgumentException("{$indices[$i]} does not exist.");
}
}
return $array;
}
print_r(removeByIndex(
[ "test1" => [ "test2" => [ "test3" => "test" ] ], "test4" => "test" ],
[ "test1", "test2", "test3" ]
));
由于我在评论中提到了这一点,因此可以(微)优化该函数,但我建议不要这样做,因为它的可读性较差,并且可能会让一些程序员感到困惑。
<?php
function removeByIndex(array $array, array $indices) {
$a =& $array;
$c = count($indices) - 1;
$i = 0;
do {
if (array_key_exists($indices[$i], $a)) {
if ($i === $c) {
unset($a[$indices[$i]]);
return $array;
}
elseif (is_array($a[$indices[$i]])) {
$a =& $a[$indices[$i]];
}
else break;
}
else break;
}
while (++$i);
throw new \InvalidArgumentException("{$indices[$i]} does not exist.");
}
关于php - 递归地从多维数组中删除特定键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26661828/