在PHP≥7.0 (使用spaceship operator <=>
)的情况下,是否有更紧凑的方式通过两个参数/字段对数组进行排序?
现在我要排序的技巧首先是第二个参数,然后是第一个参数:
// Sort by second parameter title
usort($products, function ($a, $b) {
return $a['title'] <=> $b['title']; // string
});
// Sort by first parameter brand_order
usort($products, function ($a, $b) {
return $a['brand_order'] <=> $b['brand_order']; // numeric
});
这给了我想要的结果;首先按品牌订购产品,然后按名称订购。
我只是想知道他们是否可以通过一次usort
通话来实现。
这是我的问题代码片段。可以here测试该示例。
<?php
// Example array
$products = array();
$products[] = array("title" => "Title A",
"brand_name" => "Brand B",
"brand_order" => 1);
$products[] = array("title" => "Title C",
"brand_name" => "Brand A",
"brand_order" => 0);
$products[] = array("title" => "Title E",
"brand_name" => "Brand A",
"brand_order" => 0);
$products[] = array("title" => "Title D",
"brand_name" => "Brand B",
"brand_order" => 1);
// Sort by second parameter title
usort($products, function ($a, $b) {
return $a['title'] <=> $b['title']; // string
});
// Sort by first parameter brand_order
usort($products, function ($a, $b) {
return $a['brand_order'] <=> $b['brand_order']; // numeric
});
// Output
foreach( $products as $value ){
echo $value['brand_name']." — ".$value['title']."\n";
}
?>
答案 0 :(得分:1)
usort($products, function ($a, $b) {
if ( $a['brand_order'] == $b["brand_order"] ) { //brand_order are same
return $a['title'] <=> $b['title']; //sort by title
}
return $a['brand_order'] <=> $b['brand_order']; //else sort by brand_order
});