2015-06-10 51 views
4

陣列的所有其他值我有一個數組:獲取PHP

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) 

鍵剩下的數組我怎麼可能做到這一點?

該數組的長度是主觀改變。零值也可以改變。

回答

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)

+1

還好吧......這是相當容易的。我正在尋找功能,找不到任何。也試圖做這樣的事情,但這很簡單!非常感謝! – Fl1p