views:

37

answers:

2

hi all, i've got a mysql query which spits out the following array:

Array
(
    [0] => stdClass Object
        (
            [item1] => foo 0
            [item2] => bar 0
            [catid] => 3
        )

    [1] => stdClass Object
        (
            [item1] => foo 1
            [item2] => bar 1
            [catid] => 7
        )

    [2] => stdClass Object
        (
            [item1] => foo 2
            [item2] => bar 2
            [catid] => 10
        )

    [3] => stdClass Object
        (
            [item1] => foo 3
            [item2] => bar 3
            [catid] => 7
        )

)

I was wondering if it was possible to group the array by "category", so instead of duplicate catids, there would be one catid with each object inside it.. if that makes sense? So say catid 7 would only appear once, with the two item1/item2 inside it.

+5  A: 

How about this?

foreach($results as $result) {
    $by_category[$result->catid][] = $result;
}

print_r($by_category);
Amber
@Amber, beat me to it.
tilman
thanks for that, but how do I put the items inside the appropriate categories? I still have duplicate categories :)
SoulieBaby
You're going to need to elaborate on exactly how you would want to combine them.
Amber
+2  A: 
$ret = array();
foreach ($array as $value) {
  foreach ($value as $key => $item) {
      if ($key == 'catid') continue;
      $ret[$value['catid']][] = $item;
  }
}
tilman