从数组中删除多个元素并重新索引

时间:2015-02-09 19:07:17

标签: php arrays indexing array-unset

我可以删除前三个元素以及value不等于2的所有剩余元素吗?语言是php。

print_r($array)

输出

Array ( 
    [0] => Array ( [name] => aa [value] => 0 )        
    [1] => Array ( [name] => db [value] => 1 ) 
    [2] => Array ( [name] => bc [value] => 2 )
    [3] => Array ( [name] => ba [value] => 3 ) 
    [4] => Array ( [name] => ba [value] => 0 ) 
    [5] => Array ( [name] => bc [value] => 1 )    
    [6] => Array ( [name] => aa [value] => 2 ) 
    [7] => Array ( [name] => cb [value] => 3 )
    [8] => Array ( [name] => ca [value] => 0 ) 
    [9] => Array ( [name] => dc [value] => 1 ) 
    [10] => Array ( [name] => db [value] => 2 )
    [11] => Array ( [name] => aa [value] => 3 )
    [12] => Array ( [name] => dd [value] => 0 )
    [13] => Array ( [name] => db [value] => 1 )
    [14] => Array ( [name] => bb [value] => 2 )
    [15] => Array ( [name] => ac [value] => 3 )
) 

我还需要重新索引,以便它从0开始

Array ( 
    [0] => Array ( [name] => aa [value] => 2 ) 
    [1] => Array ( [name] => db [value] => 2 )
    [2] => Array ( [name] => bb [value] => 2 )
) 

1 个答案:

答案 0 :(得分:3)

你可以这样做:

$new_array = array();

foreach ($array as $k => $v) {
    if ($k > 2 and $v['value'] != 2)
        $new_array[] = $v;
}

print_r($new_array);