1

I'm just trying to sort a multidimensional array by firstName. I've been doing a lot of research and can't really find anything similar to my issue.

(
[0] => Array
    (
        [lastName] => Mark
        [firstName] => White
    )

[1] => Array
    (
        [lastName] => Brown
        [firstName] => Peter

[2] => Array
    (
        [lastName] => Paul
        [firstName] => Vo
    )

[3] => Array
    (
        [lastName] => MCLwous
        [firstName] => Luis
    )

[4] => Array
    (
        [lastName] => Zumilia
        [firstName] => Mario
    )

[5] => Array
    (
        [lastName] => Carl
        [firstName] => Burns
    )
)
2
  • php.net/manual/en/function.array-multisort.php Commented Jun 15, 2016 at 15:14
  • @jszobody I have already looked at that one and can't really figure it out how to implemented on my task :( Commented Jun 15, 2016 at 15:15

3 Answers 3

2

You can use usort function which sorts arrays using a user-defined comparison function:

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

Or you can use sorted function from Nspl:

use function \nspl\a\sorted;
$sorted = sorted($array, 'firstName');
Sign up to request clarification or add additional context in comments.

2 Comments

@lhor Burlachenko Thanks so much!!
I really would recommend using Laravel Collections if you have access to them, they are super nice, and make for much cleaner code than using the raw php.
2

As you tagged the question laravel, I'll give you an answer that uses that framework, specifically the methods available to you when using Collections:

$sorted = collect($arr)->sortBy('firstName');

Note, that will return a laravel Collection, rather than a php array.

If you then wanted the sorted data back out as a plain php array, you would add a call to toArray at the end:

$sorted = collect($arr)->sortBy('firstName')->toArray();

Comments

0

First idea I have is to manually check each 'firstName' and keep firstName and userId in a separate dictionary. Then rearrange the elements on another empty array using the sorted dictionary (Sorting a dictionary by value or key is possible. I have seen answers to that). That's a quick answer. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.