lesssugar
lesssugar

Reputation: 16181

Merging an associalive array by specific value not working

I would like to merge the $my_array by group_order value.

Intitial $my_array structure:

array(4) {
  array(1) { 
    object(stdClass) {
      ["title"]=> string(23) "Title 1"
      ["group_order"]=> string(1) "2"
    }
  }
  array(1) {
    object(stdClass) {
      ["title"]=> string(32) "Title 2"
      ["group_order"]=> string(1) "1"
    }
  }
  array(1) {
    object(stdClass) {
      ["title"]=> string(21) "Title 3"
      ["group_order"]=> string(1) "1"
    }
  }
  array(1) {
    object(stdClass) {
      ["title"]=> string(23) "Title 4"
      ["group_order"]=> string(1) "2"
    }
  }
}

Desired result:

array(2) {
  array(2) { 
    object(stdClass) {
      ["title"]=> string(23) "Title 1"
      ["group_order"]=> string(1) "2"
    }
    object(stdClass) {
      ["title"]=> string(23) "Title 4"
      ["group_order"]=> string(1) "2"
    }
  }
  array(2) {
    object(stdClass) {
      ["title"]=> string(32) "Title 2"
      ["group_order"]=> string(1) "1"
    }
    object(stdClass) {
      ["title"]=> string(21) "Title 3"
      ["group_order"]=> string(1) "1"
    }
  }
}

I tried to do it this way:

foreach ($my_array as $row) {
    foreach ($row as $item) {
        $grouped[$item->group_order] = $row;
    }
}

But the second group element is always overwiriting the first one, and instead of array with 4 items, there's two. I tried array_merge() as well, but the outcome is the same.

Upvotes: 0

Views: 30

Answers (2)

Kouber Saparev
Kouber Saparev

Reputation: 8115

Try adding empty brackets [] at the end in order to append values to the array, and not overwrite them.

foreach ($my_array as $row) {
    foreach ($row as $item) {
        $grouped[$item->group_order][] = $item;
    }
}

Upvotes: 4

Robert Pounder
Robert Pounder

Reputation: 1511

You added a foreach you didn't need for some reason? And to keep them seperate just give them a id.

$i=0;
foreach ($myarray as $item) {
    $grouped[$item->group_order][$i] = $item;
    $i++;
}

Upvotes: 0

Related Questions