array_walk 仅部分删除匹配项
array_walk only partially removes matches
运行 进入一个奇怪的情况,使用 array_walk() 只会从我的方法中部分删除匹配项,不确定到底发生了什么。我目前正在使用 PHP v5.6.4。问题几乎似乎是它只删除了每个次要匹配项。
字距调整功能
private function strip(array $exceptions)
{
array_walk($this->hosts, function($v, $k) USE ($exceptions)
{
foreach ($exceptions AS $exception)
{
if (preg_match("/{$exception}/i", strtolower($k)))
{
unset($this->hosts[$k]); break;
}
}
});
print_r($this->hosts); die;
}
引用自PHP docs
Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.
我的重点
这与 Mark Baker 提供的信息结合使用,感谢 Mark。
private function strip(array $exceptions)
{
$this->hosts = array_filter($this->hosts, function ($k) USE ($exceptions)
{
foreach ($exceptions AS $exception)
{
if (preg_match("/{$exception}/i", strtolower($k)))
return false;
}
return true;
}, ARRAY_FILTER_USE_KEY);
return $this;
}
运行 进入一个奇怪的情况,使用 array_walk() 只会从我的方法中部分删除匹配项,不确定到底发生了什么。我目前正在使用 PHP v5.6.4。问题几乎似乎是它只删除了每个次要匹配项。
字距调整功能
private function strip(array $exceptions)
{
array_walk($this->hosts, function($v, $k) USE ($exceptions)
{
foreach ($exceptions AS $exception)
{
if (preg_match("/{$exception}/i", strtolower($k)))
{
unset($this->hosts[$k]); break;
}
}
});
print_r($this->hosts); die;
}
引用自PHP docs
Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.
我的重点
这与 Mark Baker 提供的信息结合使用,感谢 Mark。
private function strip(array $exceptions)
{
$this->hosts = array_filter($this->hosts, function ($k) USE ($exceptions)
{
foreach ($exceptions AS $exception)
{
if (preg_match("/{$exception}/i", strtolower($k)))
return false;
}
return true;
}, ARRAY_FILTER_USE_KEY);
return $this;
}