我有一个多维数组和一个数组,该数组包含该多维数组中某个元素的键。如何根据带键的数组取消设置该元素。我正在寻找无论数组尺寸如何都可以工作的代码。
以下是示例:
<?php
$array = array(
1 => array('name' => 'mike','age' => 23),
2 => array('name' => 'nick','age' => 18),
);
$keys = array(2,'name');
//
//Here code to unset that element
//
/*
//This is how the new array should be:
$array = array(
1 => array('name' => 'mike','age' => 23),
2 => array('age' => 18),
);
*/
?>
编辑:上面的代码是为了清晰。到目前为止,我可以使用unset()添加我尝试的内容,但它没有任何用处,并且会使问题不那么明确。我正在寻求正确方向的提示,而不是完全正常工作的代码。
答案 0 :(得分:1)
我找到了一个解决方案:
<?php
function unsetByKeys($keys,&$array,$path = array()){
$diff = count($keys)-count($path);
if($diff > 1){
$path[] = $keys[count($path)];
unsetByKeys($keys,$array,$path);
}else{
$lastKey = $keys[count($path)];
$subArray = &$array;
foreach($path AS $p){
$subArray = &$subArray[$p];
}
unset($subArray[$lastKey]);
}
}
$array = array(
1 => array('name' => 'mike','age' => 23),
2 => array('name' => 'nick','age' => 18),
);
$keys = array(2,'name');
unsetByKeys($keys,$array);
var_dump($array);
?>
答案 1 :(得分:-1)
代码:(http://www.tehplayground.com/#9Oup7h6gh)
// example code
$array = array(
1 => array('name' => 'mike','age' => 23),
2 => array('name' => 'nick','age' => 18),
);
$keys = array(2,'name');
unset($array[($keys[0])][($keys[1])]);
print_r($array);
/*
//This is how the new array should be:
$array = array(
1 => array('name' => 'mike','age' => 23),
2 => array('age' => 18),
);
*/
输出:
Array
(
[1] => Array
(
[name] => mike
[age] => 23
)
[2] => Array
(
[age] => 18
)
)