wit*_*ich 6 php arrays sorting usort php-7
是否有更紧凑的方法来使用 PHP \xe2\x89\xa5 7.0按两个参数/字段对数组进行排序(使用spaceship 运算符) <=>?
现在我要排序的技巧是首先按第二个参数,然后按第一个参数:
\n// Sort by second parameter title\nusort($products, function ($a, $b) {\n return $a[\'title\'] <=> $b[\'title\']; // string\n});\n\n// Sort by first parameter brand_order\nusort($products, function ($a, $b) {\n return $a[\'brand_order\'] <=> $b[\'brand_order\']; // numeric\n});\nRun Code Online (Sandbox Code Playgroud)\n这给了我我想要的结果;产品首先按品牌排序,然后按名称排序。
\n我只是想知道是否有办法做到这一点usort。
这是我的问题作为代码片段。这个例子可以在这里测试。
\n<pre><?php\n \n<!-- Example array -->\n$products = array();\n\n$products[] = array("title" => "Title A", \n "brand_name" => "Brand B",\n "brand_order" => 1);\n$products[] = array("title" => "Title C", \n "brand_name" => "Brand A",\n "brand_order" => 0);\n$products[] = array("title" => "Title E", \n "brand_name" => "Brand A",\n "brand_order" => 0);\n$products[] = array("title" => "Title D", \n "brand_name" => "Brand B",\n "brand_order" => 1);\n\n// Sort by second parameter title\nusort($products, function ($a, $b) {\n return $a[\'title\'] <=> $b[\'title\']; // string\n});\n\n// Sort by first parameter brand_order\nusort($products, function ($a, $b) {\n return $a[\'brand_order\'] <=> $b[\'brand_order\']; // numeric\n});\n\n// Output\nforeach( $products as $value ){\n echo $value[\'brand_name\']." \xe2\x80\x94 ".$value[\'title\']."\\n";\n}\n\n?></pre>Run Code Online (Sandbox Code Playgroud)\r\n类似的问题但不具体关于 php7 和太空飞船操作员已在这里得到解答:
\n\nusort($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
});
Run Code Online (Sandbox Code Playgroud)