我有这个数组
[Computers] => Array
(
[0] => Array
(
[product_id] => 78
[category_name] => Computers
[sort_order] => 1
)
[1] => Array
(
[product_id] => 70
[category_name] => Computers
[sort_order] => 1
)
)
[Scanners] => Array
(
[0] => Array
(
[product_id] => 65
[category_name] => Scanners
[sort_order] => 6
)
)
[Printers] => Array
(
[0] => Array
(
[product_id] => 58
[category_name] => Printers
[sort_order] => 3
)
)
[Screens] => Array
(
[0] => Array
(
[product_id] => 62
[category_name] => Screens
[sort_order] => 2
)
)
我似乎找不到根据关键字sort_order
对数组进行排序的方法。我尝试了这里的所有例子,但没有成功。我需要这个顺序的阵列
Computers
Screens
Printers
Scanners
试用
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
foreach ($array[$ii] as $i => $val) {
$sorter[$ii]=$val[$key];
}
}
asort($sorter);
foreach ($sorter as $element => $value) {
$ret[$element]=$array[$element];
}
$array=$ret;
}
aasort($array,"sort_order");
您只是在错误的级别上使用了排序参数。你想对最高级别进行排序,对吗?所以把排序参数也放在那里。以下数据结构更有意义:
[Computers] => Array
(
[sort_order] => 1,
[data] => array(
[0] => Array
(
[product_id] => 78,
[category_name] => Computers,
[sort_order] => 1,
)
)
)
如果你在数据结构中嵌套尽可能深的排序顺序,就会产生糟糕的排序算法。
这应该足够了:
uasort($yourArray,
create_function('$a,$b','return $a[0]["sort_order"] > $b[0]["sort_order"];'));