Forum Moderators: coopster

Message Too Old, No Replies

Grouping similar items in an array

         

londrum

9:07 pm on Jan 19, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Hello. I'm hoping that someone with more brains than me can work this out...

I've got an array which looks something like this:

$fruits = array(

1 => 'Apple',

2 => 'Banana',

3 => 'Orange',

4 => 'Apple'

)


and what i need to do is loop through and find all the identical values, and combine their keys. so it would turn into this:

$fruits = array(

'1, 4' => 'Apple',

2 => Banana,

3 => Orange

)


whilst i can easily delete the duplicate values, i cant find a way to delete them and combine their keys with the original. any ideas?

rainborick

9:32 pm on Jan 19, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I always admire folks that can come up with a super-efficient algorithm for problems like this. I usually end up brute forcing it with something like:

$new_fruits = array();

foreach ($fruits as $key => $value) {
if (array_key_exists($value, $new_fruits)) {
$new_fruits[$value] .= ",$key";
} else {
$new_fruits[$value] = $key;
} // endif
} // end foreach
$fruits = array_flip($new_fruits);

(written on the fly and untested!)

londrum

9:41 pm on Jan 19, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



cool, that looks like it might be good. let me try at work in the morning and let you know

londrum

1:23 pm on Jan 20, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



...it works perfectly, thx rainborick