使用spaceship运算符[duplicate]通过两个参数来使用数组

问题描述 投票:1回答:1

这个问题在这里已有答案:

是否有更紧凑的方法通过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电话。


这里我的questoin作为代码片段。这个例子可以测试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";
}

?>
arrays sorting php-7 usort
1个回答
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
});

Test here

© www.soinside.com 2019 - 2024. All rights reserved.