2012-06-27 131 views
0

我有一個數組:關聯數組:如何擺脫重複?

Array 
(
    [0] => Array 
     (
      [attribute_name] => Appliances 
      [attribute_value] => Washer 
     ) 

    [1] => Array 
     (
      [attribute_name] => Appliances 
      [attribute_value] => Dryer 
     ) 

    [2] => Array 
     (
      [attribute_name] => Appliances 
      [attribute_value] => Dishwasher 
     ) 

    [3] => Array 
     (
      [attribute_name] => Appliances 
      [attribute_value] => Microwave 
     ) 

    [4] => Array 
     (
      [attribute_name] => Console 
      [attribute_value] => Xbox360 
     ) 

    [5] => Array 
     (
      [attribute_name] => Console 
      [attribute_value] => PS3 
     ) 
) 

我想生產:

Array 
(
    [0] => Array 
     (
      [attribute_name] => Appliances 
      [attribute_value] => Washer, Dryer, Dishwasher, Microwave 
     ) 

    [1] => Array 
     (
      [attribute_name] => Console 
      [attribute_value] => Xbox360, PS3 
     ) 
) 

這是如何在PHP中實現?

這裏的基礎上@ andrewtweber原來的解決方案我的最終代碼:

http://codepad.org/E4WFnkbc

+4

[你嘗試過什麼?( http://whathaveyoutried.com) –

+0

將重複ES總是成對出現?重複將始終連續?會不會有雙? – Ryan

+0

@MarkReed - 以前從未看過那​​個鏈接,從現在開始不得不使用它。 :) – Duniyadnd

回答

4
$new_arr = array(); 

foreach($arr as $data) { 
    if(!isset($new_arr[$data['attribute_name']])) { 
     $new_arr[$data['attribute_name']] = array(); 
    } 
    $new_arr[$data['attribute_name']][] = $data['attribute_value']; 
} 

這會給你

array('Appliances' => array('Washer', 'Dryer', 'Dishwasher')); 

http://codepad.org/m6l3je0H

+1

完全工作!我有一個is_array部分拋出索引錯誤的問題,所以我只是用isset來代替。我已經發布了一個例子,這個例子也使得輸出成爲胡扯和笑聲的字符串。 –

+0

啊好點 - 可能只是一個通知權?但如果有其他人遇到它,我會更新我的答案 – andrewtweber