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.

0

2 Answers 2

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']);
});
Sign up to request clarification or add additional context in comments.

4 Comments

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?
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.
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.
Try using usort instead of uasort. If that doesn't work, just call array_reverse twice, to reindex it forcefully.
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);

1 Comment

Here if you want you can add multi fields for sorting

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.