I have an array like this:
$elements = array(
array("name" => "Paco", "group" => 2),
array("name" => "Juan", "group" => 3),
array("name" => "Marta", "group" => 2),
array("name" => "Julia", "group" => 4),
array("name" => "Silvia", "group" => 2)
);
I need to avoid repeating the group. If there are several elements with the same group, the final array must have only the first of each group:
$elements = array(
array("name" => "Paco", "group" => 2),
array("name" => "Juan", "group" => 3),
array("name" => "Julia", "group" => 4)
);
Is there a better way than foreaching the array and processing each row? Something like GROUP BY in SQL?
Seeing as a lot of strange code has come up, some are wildly inefficient or just strange in my opinion:
And what you should have now is an array where only the FIRST occurence of a group is saved and only requires one pass, O(N). If you don’t want the index to be the group id then just do:
PS. If you really dislike array_values(), then you could also do it like this (or some variation of this):