如何使用 PHP 中包含的关联数组的子字段对关联数组进行排序?
如何按关联数组的值之一对关联数组进行排序?
例如:
$arr = array(
'ted' => array( 'age' => 27 ),
'bob' => array( 'age' => 18 ),
'jay' => array( 'age' => 24 )
);
$arr = ???
foreach ($arr as $person)
echo $person['age'], ', ';
因此输出为:
18, 24, 27
这是一个过于简单的示例,只是为了演示我的问题。
我仍然要求 $arr
是一个关联数组。
How can I sort an associative array by one of its values?
For example:
$arr = array(
'ted' => array( 'age' => 27 ),
'bob' => array( 'age' => 18 ),
'jay' => array( 'age' => 24 )
);
$arr = ???
foreach ($arr as $person)
echo $person['age'], ', ';
So that the output is:
18, 24, 27
This is an oversimplified example just to demonstrate my question.
I still require that $arr
is an associative array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
uasort()
< /a> 函数允许您指定一个回调函数,该函数将负责在两个元素之间进行比较 - 因此,如果您实现了正确的回调函数,应该会做得很好。在这里,您必须实现一个回调函数来接收两个数组 - 并比较
age
项:在以下代码部分中使用该函数:
您将得到这个结果数组:
The
uasort()
function allows you to specify a callback function, which will be responsible of doing the comparison between two elements -- so, should do just well, if you implement the proper callback function.Here, you'd have to implement a callback function that will receive two arrays -- and compmare the
age
item :Using that function in the following portion of code :
You would get you this resulting array :
这是 PHP 5.3 匿名函数派上用场的经典示例:
$a['age'] - $b['age']
是一个小技巧。它之所以有效,是因为回调函数预计返回一个值 < 0 表示$a
小于$b
并且值 >0如果$a
大于$b
,则为 0。This is a classical example where PHP 5.3 anonymous functions come in handy:
The
$a['age'] - $b['age']
is a small trick. It works because the callback function is expected to return a value < 0 is$a
is smaller than$b
and a value > 0 if$a
is bigger than$b
.由于您要对子数组内的值进行排序,因此没有一个内置函数可以完成 100% 的工作。我会进行用户定义的排序:
http://www.php.net /manual/en/function.uasort.php
这是一个示例比较函数,它根据嵌套数组中的该值返回其比较
Since you're sorting on a value inside a sub array, there's not a built-in function that will do 100% of the work. I would do a user-defined sort with:
http://www.php.net/manual/en/function.uasort.php
Here's an example comparison function that returns its comparison based on this value in the nested array
http://www.php.net/manual/en/array.sorting.php
这种特殊情况将涉及使用一种使用回调进行排序的排序方法
http://www.php.net/manual/en/array.sorting.php
This particular case will involve using one of the sort methods that use a callback to sort
您不仅对关联数组进行排序,而且对关联数组的关联数组进行排序;)
A uasort 电话就是你想要的
You're not just sorting an associative array, you're sorting an associative array of associative arrays ;)
A uasort call is what you're after