【发布时间】:2020-12-27 14:56:04
【问题描述】:
原始数组:
[0] => Array
(
[name] => Light Amethyst
[description] => color
)
[1] => Array
(
[name] => Stone
[description] => base material
)
[2] => Array
(
[name] => Emerald
[description] => color
)
[3] => Array
(
[name] => Brass
[description] => base material
)
通过以下函数应用usort($terms, "mysort");
function getSortOrder($c) {
$sortOrder = array(
"base material",
"color"
);
$pos = array_search($c['description'], $sortOrder);
return $pos !== false ? $pos : 99999;
}
function mysort($a, $b) {
if( getSortOrder($a) < getSortOrder($b) ) {
return -1;
}elseif( getSortOrder($a) == getSortOrder($b) ) {
return 0;
}else {
return 1;
}
}
这成功通过getSortOrder函数中的$sortOrder数组排序数组(先基材,后颜色)
[0] => Array
(
[name] => Stone
[description] => base material
)
[1] => Array
(
[name] => Brass
[description] => base material
)
[2] => Array
(
[name] => Light Amethyst
[description] => color
)
[3] => Array
(
[name] => Emerald
[description] => color
)
现在我正在尝试按name 对这个新的排序数组进行排序,同时保持之前应用的排序顺序(首先是基础材料,然后是颜色)。
预期输出:
[0] => Array
(
[name] => Brass
[description] => base material
)
[1] => Array
(
[name] => Stone
[description] => base material
)
[2] => Array
(
[name] => Emerald
[description] => color
)
[3] => Array
(
[name] => Light Amethyst
[description] => color
)
通常我可以像这样应用usort 函数:
usort($people,"sort_name");
function sort_name($a,$b)
{
return $a["name"] > $b["name"];
}
但这当然会弄乱原始 description 排序的输出。
如何像上面的函数一样先按description 排序,然后继续按name 排序,同时保持description 排序不变?
【问题讨论】:
标签: php arrays sorting multidimensional-array