[英]Sorting alphabetically by Array Value in Multidimensional Indexed Array After Custom Sort (usort) / Sort Array by Two Values
原始数组:
[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
function 中的$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
对这个新的排序数组进行排序,同时保持先前应用的排序顺序(首先是基础材料,然后是颜色)。
预期 Output:
[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
function :
usort($people,"sort_name");
function sort_name($a,$b)
{
return $a["name"] > $b["name"];
}
但这当然会弄乱原始description
排序的 output。
我怎样才能像上面的函数一样先按description
排序,然后在保持description
排序的同时继续按name
排序?
您可以使用array_multisort将一个 go 中的原始数据排序为预期的 output (先按描述排序,然后按名称排序),如下所示
$data = [
['name' => 'Light Amethyst', 'description' => 'color'],
['name' => 'Stone', 'description' => 'base material'],
['name' => 'Emerald', 'description' => 'color'],
['name' => 'Brass', 'description' => 'base material']
];
array_multisort(array_column($data, 'description'), SORT_ASC, array_column($data, 'name'), SORT_ASC, $data);
$data
现在将首先按description
排序,然后按name
排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.