php中的array_walk无法unset引用数组,大家看看代码有没有什么问题?

WBOY
Release: 2016-06-06 20:37:47
Original
942 people have browsed it

代码如下:

<code>    $array = array(0 => 'bar', 1 => 'bat', 2=>'bar', 3=>'car', 4=>'buy',5=>'foo');
array_walk($array, function($val,$key) use(&$array){

    if(strpos($val, 'b')!==false){
        unset($array[$key]);
    }
});

    var_dump($array);
</code>
Copy after login
Copy after login

输出:

<code>array(3) { [1]=> string(3) "bat" [3]=> string(3) "car" [5]=> string(3) "foo" }
</code>
Copy after login
Copy after login

回复内容:

代码如下:

<code>    $array = array(0 => 'bar', 1 => 'bat', 2=>'bar', 3=>'car', 4=>'buy',5=>'foo');
array_walk($array, function($val,$key) use(&$array){

    if(strpos($val, 'b')!==false){
        unset($array[$key]);
    }
});

    var_dump($array);
</code>
Copy after login
Copy after login

输出:

<code>array(3) { [1]=> string(3) "bat" [3]=> string(3) "car" [5]=> string(3) "foo" }
</code>
Copy after login
Copy after login

try php array_filter

<code>php</code><code> $array = array(0 => 'bar', 1 => 'bat', 2=>'bar', 3=>'car', 4=>'buy',5=>'foo');
array_walk($array, function($val,$key) use(&$array){
    echo $val."\n";
    if(strpos($val, 'b')!==false){
        unset($array[$key]);
    }
});

    var_dump($array);
</code>
Copy after login

输出

<code>bar
bar
buy
array(3) {
  [1] =>
  string(3) "bat"
  [3] =>
  string(3) "car"
  [5] =>
  string(3) "foo"
}
</code>
Copy after login

输出这个$val就能看出端倪了。

第一次unset
变成
0 => 'bat',
1 => 'bar',
2 => 'car',
3 => 'buy',
4 => 'foo'
数组第二次遍历,读取索引为1的数据
所以unset($array[1]) 这时候消除的就是bar
以此类推。

一般在遍历数组的时候去删除数组的中的元素是非常不建议的。
会造成迭代器指向混乱。

一般的方案是把要删除的数据放入一个新的数组里。然后再去遍历这个要删除的数组 再去删除原来的元素。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template