按数组元素对一组多维数组进行排序
问题描述:
假设我从这里开始:
$arr[0] = array('a' => 'a', 'int' => 10);
$arr[1] = array('a' => 'foo', 'int' => 5);
$arr[2] = array('a' => 'bar', 'int' => 12);
我想去这里
$arr[0] = array('a' => 'foo', 'int' => 5);
$arr[1] = array('a' => 'a', 'int' => 10);
$arr[2] = array('a' => 'bar', 'int' => 12);
如何按这些元素的元素对数组中的元素进行排序?
How can I sort the elements in an array by those elements' elements?
多维数组的感觉总是超出我的大脑所能承受的范围(-_-)(直到我弄清楚它们,而且它们看起来非常简单)
Multidimensional arrays always feel like a little bit more than my brain can handle (-_-) (until I figure them out and they seem super easy)
答
是否要通过"int"键的值对其进行排序?
Do you want to order them by the value of the "int" key ?
将 uasort 与回调函数一起使用:
Use uasort with a callback function :
function compare_by_int_key($a, $b) {
if ($a['int'] == $b['int']) {
return 0;
}
return ($a['int'] < $b['int']) ? -1 : 1;
}
uasort($arr, "compare_by_int_key");