2015-11-03 191 views
-3

我在PHP中有下面的數組。 Id和Total鍵對於相同的Id值是相同的。在PHP中合併具有相同ID值的數組元素

Array 
(
    [0] => Array 
     (
      [id] => 1 
      [total] => 100 
      [line] => books 
      [value] => 10 
     ) 
    [1] => Array 
     (
      [id] => 1 
      [total] => 100 
      [line] => cars 
      [value] => 50 
     ) 
    [2] => Array 
     (
      [id] => 1 
      [total] => 100 
      [line] => cover 
      [value] => 30 
     ) 
    [3] => Array 
     (
      [id] => 2 
      [total] => 80 
      [line] => books 
      [value] => 5 
     ) 
    [4] => Array 
     (
      [id] => 2 
      [total] => 80 
      [line] => cover 
      [value] => 35 
     ) 
    [5] => Array 
     (
      [id] => 2 
      [total] => 80 
      [line] => cars 
      [value] => 40 
     ) 

我想合併數組內線路和Value元素。 爲了說明我看到的結果是下面的數組。

Array 
(
    [0] => Array 
     (
      [id]  => 1 
      [total] => 100 
      [details] => Array 
       (
        [0] => Array 
         (
         [line] => books 
         [value] => 10 
        ) 
        [1] => Array 
         (
         [line] => cars 
         [value] => 50 
        ) 
        [2] => Array 
         (
         [line] => cover 
         [value] => 30 
        ) 
       ) 
     )      

    ) 
    [1] => Array 
     (
      [id]  => 2 
      [total] => 80 
      [details] => Array 
       (
        [0] => Array 
         (
         [line] => books 
         [value] => 5 
        ) 
        [1] => Array 
         (
         [line] => cars 
         [value] => 35 
        ) 
        [2] => Array 
         (
         [line] => cover 
         [value] => 40 
        ) 
       ) 
     )      
    ) 

我正在使用PHP。謝謝你的幫助。

+2

簡單的foreach循環將工作 - 你需要在最少嘗試一下 – 2015-11-03 23:55:00

+0

歡迎來到Stack Overflow。請發佈您迄今爲止的嘗試。 – Twisty

回答

5

不夠好無聊地做你的工作\功課你:

$out=array(); 
foreach($array as $x){ 
    $out[$x['id']]['id']=$x['id']; 
    $out[$x['id']]['total']=$x['total']; 
    $out[$x['id']]['details'][]=array('line'=>$x['line'],'value'=>$x['value']); 
} 

注:

  • 使用id作爲了重點,可以加入我們自己的,但是這將工作 罰款。
  • ID和總將在(每個鍵)每個迴路被覆蓋,但是這不是什麼大不了的
  • 線\值中有自己的細節陣列增加
+0

哈哈,你是完全正確的,對不起,我心中有這麼多東西,我選擇發佈我的問題。 PS:這是我的第一篇文章,我不確定如何將這個問題標記爲正確的答案。 – user3216926

+0

@ user3216926在問題左側的投票下應該有一個複選標記,點擊它會變成綠色:http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – 2015-11-04 02:08:15

+0

我喜歡另一種綠色$$$$$ –

相關問題