【问题标题】:usort array by two parameters using spaceship operator [duplicate]使用宇宙飞船运算符按两个参数对数组进行排序[重复]
【发布时间】:2019-07-24 21:31:15
【问题描述】:

有没有更紧凑的方法来通过两个参数/字段对数组进行排序,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 来电。


这里我的问题是代码 sn-p。这个例子可以测试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";
}

?>

【问题讨论】:

  • return $a['brand_order'] &lt;=&gt; $b['brand_order'] ?: $a['title'] &lt;=&gt; $b['title'] – 不能保证您所做的工作,因为不能保证排序是稳定的。
  • @deceze 这个问题是关于 php7 和宇宙飞船操作员的,我认为这在其他答案中没有明确回答......
  • 宇宙飞船操作员并没有使这个问题独一无二。独特的部分是通过两个不同的条件进行比较。事实上,这两个主题都在副本中进行了讨论。也许不完全是这种组合,但肯定足够接近,您可以将信息组合成适合您情况的代码。

标签: php arrays sorting php-7 usort


【解决方案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

【讨论】:

  • 谢谢,这就是我想要的。现在我读到你的代码,它也很合乎逻辑。
猜你喜欢
  • 2019-08-10
  • 2010-11-25
  • 2011-01-30
  • 2023-03-30
  • 2011-03-04
  • 2010-10-24
  • 1970-01-01
  • 2021-08-07
相关资源
最近更新 更多