progx progx - 5 months ago 17
PHP Question

How to sort a multidimensional array by firstName in php?

I have a multidimensional array that is being sorted by groupName (The part works just fine)and inside each group I have values (groupName, firstName, lastName, etc). Basically I'm trying to sort each group inside this multidimensional array by firstName and I'm not sure where to start :(. Here's my mutidimensional array:

function group_assoc($array, $key)
{
$array_of_groups = array();
foreach ($array as $value) {
$array_of_groups[$value[$key]][] = $value;
}
return $array_of_groups;
}


$somearray = array(
array('groupName' => 'Group1', 'phoneNumber' => 13037777777, 'firstName'=>'Jeff','lastName' => 'Jeff'),
array('groupName' => 'Group2', 'phoneNumber' => 13033213453, 'firstName'=>'Zumia','lastName' => 'Brown'),
array('groupName' => 'Group3', 'phoneNumber' => 13030098342, 'firstName'=>'Junior','lastName' => 'White'),
array('groupName' => 'Group2', 'phoneNumber' => 13039899231, 'firstName'=>'Ana','lastName' => 'McLwius'),
array('groupName' => 'Group1', 'phoneNumber' => 13033422109, 'firstName'=>'first','lastName' => 'last'),
array('groupName' => 'Group3', 'phoneNumber' => 13033222098, 'firstName'=>'Junior','lastName' => 'Smith')
);


$account_requests = group_assoc($somearray, 'groupName');
print_r($account_request);


and printing the array I get this:

Array
(
[Group1] => Array
(
[0] => Array
(
[groupName] => Group1
[phoneNumber] => 13037777777
[firstName] => Mike
[lastName] => Jeff
)

[1] => Array
(
[groupName] => Group1
[phoneNumber] => 13033422109
[firstName] => Ben
[lastName] => Morris
)

)

[Group2] => Array
(
[0] => Array
(
[groupName] => Group2
[phoneNumber] => 13033213453
[firstName] => Zumia
[lastName] => Brown
)

[1] => Array
(
[groupName] => Group2
[phoneNumber] => 13039899231
[firstName] => Ana
[lastName] => McLwius
)

)

[Group3] => Array
(
[0] => Array
(
[groupName] => Group3
[phoneNumber] => 13030098342
[firstName] => Junior
[lastName] => White
)

[1] => Array
(
[groupName] => Group3
[phoneNumber] => 13033222098
[firstName] => Junior
[lastName] => Smith
)

)

)


I know if it was a simple array (not a multidimensional array) I can just do:

usort($peopleArray, function ($v1, $v2) {
return strcmp($v1['firstName'], $v2['firstName']);
});


Any ideas on how to accomplish this please? Thanks a lot in advance!

Answer

First create groups with proper items, then sort each group:

$groups = array();
foreach ($someArray as $item) {
    $groupName = $item['groupName'];
    if (!isset($groups[$groupName])) {
        $groups[$groupName] = array();
    }
    $groups[$groupName][] = $item;
}

foreach ($groups as &$group) {
    usort($group, function ($v1, $v2) {
        return strcmp($v1['firstName'], $v2['firstName']);
    });
}