0

I have an array of users, and I want to sort them alphabetically according to their first_names. But the thing is I am keeping first_name, last_name in another array of the array elements.

Let me explain with the code:

$users = [
    [
        'id' => 1,
        'username' => 'asd',
        'info' => ['first_name' => 'John', 'last_name' => 'Doe']
    ],
    [
        'id' => 2,
        'username' => 'martin',
        'info' => ['first_name' => 'Martin', 'last_name' => 'Brown']
    ]
];

I want to sort this $users array according to the values of the first_name.

I couldn't find any solutions, maybe it's because I couldn't be able to understand the logic of the array_filter, array_map, or any other array functions that I can use.

Any help would be really helpful to me.

Rudi Visser
  • 20,568
  • 5
  • 66
  • 95
Umut Sirin
  • 2,442
  • 1
  • 19
  • 31

2 Answers2

4

You can use uasort for this, with a callback that simply compares the names.

function fncompare($a, $b)
{
    return strcmp($a['info']['first_name'], $b['info']['first_name']);
}

uasort($users, "fncompare");

The examples in the documentation are very clear.


Since you're on PHP5.4 there, you can make this look a little neater with an anonymous function, as you're probably not going to use this method outside of the sorting:

uasort($users, function($a, $b) {
    return strcmp($a['info']['first_name'], $b['info']['first_name']);
});
Rudi Visser
  • 20,568
  • 5
  • 66
  • 95
  • Thank you dude, it's really great solution, but I am just wondering, what is the performance of this code, would it be useful for sorting 1000 items too? – Umut Sirin Mar 15 '13 at 10:02
  • Yes, it's going to go over each item and run the callback for comparison. No matter on the sort method, this is going to happen. – Rudi Visser Mar 15 '13 at 10:09
  • Thank you so much again. – Umut Sirin Mar 15 '13 at 10:11
  • One little question, it didn't change the index values of the array, even though it changed the sort. I mean, the value array with the index key 0 is still 0. I really need them to be sorted as well. – Umut Sirin Mar 15 '13 at 10:39
  • Try using `usort` instead of `uasort`. If that doesn't work, just call `array_reverse` twice, to reindex it forcefully. – Rudi Visser Mar 15 '13 at 10:44
0

Try this : use array_multisort :http://www.php.net/manual/en/function.array-multisort.php

$arr = array(
    array(
        'id' => 1,
        'username' => 'asd',
        'info' => array('first_name' => 'John', 'last_name' => 'Doe')
    ),
    array(
        'id' => 2,
        'username' => 'martin',
        'info' => array('first_name' => 'Martin', 'last_name' => 'Brown')
    )
);


$sort = array();
foreach($arr as $k=>$v) {
    $sort['first_name'][$k] = $v['info']['first_name']; 
}

array_multisort($sort['first_name'], SORT_ASC, $arr);

echo "<pre>";
print_r($arr);
Prasanth Bendra
  • 29,105
  • 8
  • 50
  • 70