1

如果我希望代码看起来像这样,有没有办法

foreach ($a as $key=>$value) {
    if (( $value['someprop'] == 'some prop' ) || ( $value['someprop'] == 'some other prop' ))
        array_splice($a, $key, 1); 

因为数组键是用 array_splice 移动的

4

2 回答 2

1

使用 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); 
}
于 2015-11-02T10:36:11.583 回答
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
        )

)

http://php.net/manual/en/function.array-filter.php

于 2015-11-02T11:44:38.947 回答