当前位置: 动力学知识库 > 问答 > 编程问答 >

How to sort a multidimensional array by First Name in php?

问题描述:

I've been pulling my hair out for the past 2 hours now. 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 :(. Can anyone help me please? Thanks a lot!!

(

[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

)

)

网友答案:

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');
网友答案:

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();

网友答案:

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. :)

分享给朋友:
您可能感兴趣的文章:
随机阅读: