0

I have an array:

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 ) ) 

I want to produce:

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

How is this achieved in PHP?

Here's my final code based on @andrewtweber's original solution:

http://codepad.org/E4WFnkbc

8
  • 4
    What have you tried? Commented Jun 27, 2012 at 23:25
  • Will the duplicates always come in pairs? Will the duplicates always be consecutive? Will there always be pairs? Commented Jun 27, 2012 at 23:26
  • @MarkReed - never saw that link before, going to have to use it from now on. :) Commented Jun 27, 2012 at 23:26
  • 2
    Can I suggest instead of combining them into a comma-separated list, that you combine them into another sub-array? array(0=> array('attribute_name' => "Appliances", 'attribute_value' => array('Washer','Dryer','Diswasher'))) Commented Jun 27, 2012 at 23:26
  • Or what about array( 'Appliances' => array('Washer', 'Dryer', 'Dishwasher') ) Commented Jun 27, 2012 at 23:33

1 Answer 1

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']; } 

This will give you

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

http://codepad.org/m6l3je0H

Sign up to request clarification or add additional context in comments.

2 Comments

That totally worked! I had an issue with the is_array part throwing an indexing error so I just used isset instead. I've posted an example that also makes the output into a string for craps and laughs.
Ah good point - probably just a notice right? But I'll update my answer in case anybody else comes across it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.