简体   繁体   English

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

[英]Get every other value of array in PHP

I have an array: 我有一个数组:

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 )

It had more values, but I filtered out the zero values, because I don't need them. 它有更多的值,但我过滤掉了零值,因为我不需要它们。

Now I need every other value, so that I get: 现在我需要所有其他价值,以便我得到:

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

I also need the remaining array with the keys intact 我还需要剩下的数组,键完好无损

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

How can I possibly do this? 我怎么可能这样做?

The length of the array is subjectible to change. 阵列的长度可以改变。 Also the zero values can change. 零值也可以改变。

Try as 试试吧

$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++;
}

Using array_walk function 使用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) 小提琴(array_walk)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM