I have a query from eloquent which I transform into an array. My goal is to group multiples of members into their respective group based on their group id, which each member holds. So essentially I would need a three dimensional array, with the first array holding the group ids, the second holding an array of each member, and the third holding that members information i.e.
Array(
[1] => array(
array( [member_id] => 3
[type] => human
[group_id] => 1
),
array( [member_id] => 4
[type] => alien
[group_id] => 1
),
)
[2] => array(
array( [member_id] => 9
[type] => human
[group_id] => 2
),
array( [member_id] => 10
[type] => alien
[group_id] => 2
),
)
)
I've tried a few things, the one that has gotten me closest to this goal is the following:
Sorting them by their group gives me a two dimensional array with the members being returned in ascending order, like so:
Array
(
[0] => Array
(
[member_id] => 7
[type] => human
[group_id] => 1
)
[1] => Array
(
[customer_id] => 5
[type] => alien
[group_id] => 1
)
[2] => Array
(
[customer_id] => 8
[type] => alien
[group_id] => 2
)
//there is no group #3, so next group is 4
[3] => Array
(
[customer_id] => 3
[type] => human
[group_id] => 4
)
)
But the keys are not based on group ids, they're just assigned by the function.
To make the first arrays keys actual group ids, I did the following:
$sorted = array();
$i=0;
while($i <= count($members))
{
foreach($members as $member)
{
if($member['group_id'] == $i)
{
$sorted[$i] = $member;
}
}
echo $i;
$i++;
}
But this gave me only the first member for each group and not any more.
SOLUTION: I hope it's still okay to post the answer in my question, it just came to me while I was writing out this question lol...
I wasn't actually creating another array within $sorted[] in my if condition, so that's why it didn't append the other members, only one. I added a pair of brackets:
$sorted[$i][] = $member;
and it works :). Hope it helps someone in the future.