2013-12-03 35 views
-3

原始數組:
多重陣列合併成新的數組與關鍵

$cat = Array ( 
    [0] => Array ([id] => 2 [name] => W [pid] => 1) 
    [1] => Array ([id] => 4 [name] => M [pid] => 1) 
    [2] => Array ([id] => 5 [name] => C [pid] => 1) 
    [3] => Array ([id] => 8 [name] => K [pid] => 7) 
    [4] => Array ([id] => 9 [name] => B [pid] => 7) 
    [5] => Array ([id] => 12 [name] => X [pid] => 11) 
) 

我要得到這個結果:

$cat = Array ( 
    [0] => Array (
     [pid]=>1, 
     [item] => Array(
      [0] => Array ([id] => 2 [name] => W), 
      [1] => Array ([id] => 4 [name] => M), 
      [2] => Array ([id] => 5 [name] => C) 
     ) 
    ), 
    [1] => Array (
     [pid]=>7, 
     [item]=>Array(
      [0] => Array ([id] => 8 [name] => K), 
      [0] => Array ([id] => 9 [name] => B) 
     ) 
    ), 
    [2] => Array (
     [pid]=>11, 
     [item]=>Array(
      [0] => Array ([id] => 12 [name] => X) 
     ) 
    ) 
) 

如何?

+0

所以,要合併都具有相同的'pid'的項目?你有沒有嘗試過任何東西?我們喜歡在這裏幫助,但你需要展示你的嘗試。你卡在哪裏?你需要什麼幫助?我們不會爲你做這件事。 –

+0

@meda:只需粘貼鏈接。所以你會把它鏈接起來。 –

+0

請閱讀['merge_array'](http://us1.php.net/array_merge) – meda

回答

0
$newCat = array(); 
array_walk($cat, function($v) use(&$newCat){ 
    $i = $v['pid']; 
    unset($v['pid']); 
    if(!isset($newCat[$i])) 
     $newCat[$i] = array('pid' => $i, 'item' => array()); 
    $newCat[$i]['item'][] = $v; 
}); 

print_r(array_values($newCat)); 

demo

+0

工作正常!謝謝你使者! – user3062694