我有一个数组:
Array
(
[5] => Array
(
[0] => 19
[1] => 18
)
[6] => Array
(
[0] => 28
)
)
和我试图删除元素的值使用我的函数:
function removeElementWithValue($obj, $delete_value){
if (!empty($obj->field)) {
foreach($obj->field as $key =>$value){
if (!empty($value)) {
foreach($value as $k=>$v){
if($v == $delete_value){
$obj->field[$key][$k] = '';
}
}
}
}
}
return urldecode(http_build_query($obj->field));
}
echo removeElementWithValue($request, '19');
术后上面我有: 5 [0] =, 5 [1] = 18, 6 [0] = 28; //右! !
echo removeElementWithValue($request, '18');
术后上面我有: 5 [0] =, 5 [1] =, 6 [0] = 28; //错了吗? ?
但第二次操作后的预期结果是:
5[0]=19&5[1]=&6[0]=28;
我错在哪里?谢谢!
使用array_walk_recursive查找和修改值
$arr = Array (
5 => Array ( 0 => 19, 1 => 18 ),
6 => Array ( 0 => 28));
$value = 18;
array_walk_recursive($arr,
function (&$item, $key, $v) { if ($item == $v) $item = ''; }, $value);
print_r($arr);
结果:Array (
5 => Array ( 0 => 19, 1 => ),
6 => Array ( 0 => 28));
更简单的函数可能是…
function removeElementWithValue($ar,$val){
foreach($ar as $k=>$array){
//update the original value with a new array
$new_ar = array_diff_key($array,array_flip(array_keys($array,$val)));
if($new_ar){
$ar[$k]=$new_ar;
}else{
unset($ar[$k]);//or remove the empty value
}
}
return $ar;
}