如何使用PHP中包含关联数组的子字段进行排序关联数组? [英] How to sort associative array using sub-field of contained associative arrays in PHP?
问题描述
我如何可以通过其值之一排序的关联数组?
How can I sort an associative array by one of its values?
例如:
$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.
推荐答案
< STRONG> uasort()
功能允许您指定一个回调函数,这将是负责做两个元素之间的比较 - 所以,应该做的很好,如果实现了正确的回调函数。
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.
在这里,你必须实现将接收两个数组一个回调函数 - 和compmare的年龄
项目:
Here, you'd have to implement a callback function that will receive two arrays -- and compmare the age
item :
function callback($a, $b) {
if ($a['age'] > $b['age']) {
return 1;
} else if ($a['age'] < $b['age']) {
return -1;
}
return 0;
}
结果
在code的以下部分使用该功能:
Using that function in the following portion of code :
$arr = array(
'ted' => array( 'age' => 27 ),
'bob' => array( 'age' => 18 ),
'jay' => array( 'age' => 24 )
);
uasort($arr, 'callback');
var_dump($arr);
您会得到你该得到的数组:
You would get you this resulting array :
array
'bob' =>
array
'age' => int 18
'jay' =>
array
'age' => int 24
'ted' =>
array
'age' => int 27
这篇关于如何使用PHP中包含关联数组的子字段进行排序关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!