2016-10-06 90 views
0

我有一個這樣的數組:如何在PHP中整合這個數組的重複元素?

$array = array(
    0 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "memory"), 
    1 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "cpu"), 
    2 => array("ordernumber" => "1", "name" => "John", "product" => "desktop", "component" => "cpu"), 
    3 => array("ordernumber" => "2", "name" => "Pete", "product" => "monitor", "component" => "") 
); 

它包含了從不同的訂單數據,但你可以看到一個訂單可以包含多個購買的產品,每個產品可以包含不同的「分量」。在這個陣列中有很多重複的數據,所以我想把它變成這樣:

$array = array(
    0 => array(
     "order" => array(
      "ordernumber" => "1", "name" => "John" 
     ), 
     "products" => array(
      0 => array(
       "name" => "laptop", 
       "components" => array("memory", "cpu") 
      ), 
      1 => array(
       "name" => "desktop", 
       "components" => array("cpu") 
      ) 
     ) 
    ), 
    1 => array(
     "order" => array(
      "ordernumber" => "2", "name" => "Pete" 
     ), 
     "products" => array(
      0 => array(
       "name" => "monitor", 
       "components" => array() 
      ) 
     ) 
    ) 
); 

這將是一個很好的方法來做到這一點?

+0

使用foreach循環並相應地修改數據。你有什麼嘗試? – jitendrapurohit

+0

我對數組不熟悉,所以我甚至無法想象循環(或者組成新數組)實際上應該是什麼樣子。感謝下面的解決方案,我對未來如何解決類似問題有了更清晰的瞭解。 – Marc

回答

1

請使用下面的代碼,以使溶液想要

<?php 

$array = array(
    0 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "memory"), 
    1 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "cpu"), 
    2 => array("ordernumber" => "1", "name" => "John", "product" => "desktop", "component" => "cpu"), 
    3 => array("ordernumber" => "2", "name" => "Pete", "product" => "monitor", "component" => "") 
); 



$final_array = []; 
foreach($array as $k=>$v){ 
    $final_array[$v['ordernumber']]['order']['ordernumber'] = $v['ordernumber']; 
    $final_array[$v['ordernumber']]['order']['name'] = $v['name']; 

    $final_array[$v['ordernumber']]['products'][$v['product']]['name'] = $v['product']; 
    $final_array[$v['ordernumber']]['products'][$v['product']]['components'][] = $v['component']; 
} 

// You can skip this foreach if there will not metter of KEY of an array in your code! 
$final_array = array_values($final_array); 
foreach($final_array as $k=>$v){ 
    $final_array[$k]['products'] = array_values($final_array[$k]['products']); 
} 


echo "<pre>"; 
print_r($final_array); 

?> 

它應該工作什麼!

+0

謝謝,它完美的作品! – Marc

+0

您的歡迎:) –