如果我希望代码看起来像这样,有没有办法
foreach ($a as $key=>$value) {
if (( $value['someprop'] == 'some prop' ) || ( $value['someprop'] == 'some other prop' ))
array_splice($a, $key, 1);
因为数组键是用 array_splice 移动的
如果我希望代码看起来像这样,有没有办法
foreach ($a as $key=>$value) {
if (( $value['someprop'] == 'some prop' ) || ( $value['someprop'] == 'some other prop' ))
array_splice($a, $key, 1);
因为数组键是用 array_splice 移动的
使用 for 循环,从数组末尾倒数:
(这样你就不会因为索引的变化而遇到麻烦)
for($i = count($myArray); $i>0; $i--)
{
$value = $myArray[$i];
if (( $value['someprop'] == 'some prop' ) || ( $value['someprop'] == 'some other prop' ))
array_splice($myArray, $i-1, 1);
}
改用更优雅的array_filter
:
$a = [
['someprop' => 'some prop'],
['someprop' => 'not some prop'],
['someprop' => 'some other prop'],
];
方法:
$filtered = array_filter($a, function($value) {
return !($value['someprop'] == 'some prop' || $value['someprop'] == 'some other prop');
});
打印_r($过滤):
Array
(
[1] => Array
(
[someprop] => not some prop
)
)