在PHP中获取数组的每个其他值

时间:2015-06-10 09:58:23

标签: php arrays for-loop filter

我有一个数组:

Array ( [A] => 4 [B] => 4 [D] => 4 [E] => 8 [F] => 4 [G] => 8 [H] => 8 [J] => 12 [K] => 12 [L] => 11 [M] => 11 [O] => 10 [P] => 10 [Q] => 10 [R] => 10 )

它有更多的值,但我过滤掉了零值,因为我不需要它们。

现在我需要所有其他值,以便我得到:

Array ( [A] => 4 [D] => 4 [F] => 4 [H] => 8 [K] => 12 [M] => 11 [P] => 10 [R] => 10 )

我还需要保持密钥完好的剩余数组

Array ( [B] => 4 [E] => 8 [G] => 8 [J] => 12 [L] => 11 [O] => 10 [Q] => 10 )

我怎么可能这样做?

阵列的长度可以改变。零值也可以改变。

1 个答案:

答案 0 :(得分:5)

尝试

$arr = Array ( 'A' => 4, 'B' => 4, 'D' => 4, 'E' => 8, 'F' => 4, 'G' => 8, 'H' => 8, 'J' => 12, 'K' => 12, 'L' => 11, 'M' => 11, 'O' => 10, 'P' => 10, 'Q' => 10, 'R' => 10 );

$arr1 = array();
$arr2 = array();

$i = 0;
foreach($arr as $key => $value){
    if($i%2 == 0){
        $arr1[$key] = $value;
    }else{
        $arr2[$key] = $value;
    }
    $i++;
}

使用array_walk功能

$current = 0;

array_walk($arr,function($v,$k) use(&$result,&$current){
               if($current%2 == 0) {
                   $result['even'][$k] = $v;
               }else{
                   $result['odd'][$k] = $v;
               }
               $current++;
           });
print_r($result);

Fiddle

Fiddle(array_walk)