在array_walk_recursive中取消设置不起作用

Joh*_*ith 3 php arrays

  array_walk_recursive($arr, function(&$val, $key){
    if($val == 'smth'){
      unset($val);          // <- not working, unset($key) doesn't either
      $var = null;          // <- setting it to null works
    }
  });

  print_r($arr);
Run Code Online (Sandbox Code Playgroud)

我不希望它为null,我希望元素完全脱离数组.这甚至可以用array_walk_recursive吗?

dfs*_*fsq 9

你不能array_walk_recursive在这里使用,但你可以编写自己的功能.这很简单:

function array_unset_recursive(&$array, $remove) {
    if (!is_array($remove)) $remove = array($remove);
    foreach ($array as $key => &$value) {
        if (in_array($value, $remove)) unset($array[$key]);
        else if (is_array($value)) {
            array_unset_recursive($value, $remove);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

array_unset_recursive($arr, 'smth');
Run Code Online (Sandbox Code Playgroud)

或删除几个值:

array_unset_recursive($arr, array('smth', 51));
Run Code Online (Sandbox Code Playgroud)


Nik*_*kiC 5

unset($val)只会删除局部$val变量.

没有(理智的)方法如何从内部数组中删除元素array_walk_recursive.您可能必须编写自定义递归函数来执行此操作.