【问题标题】:PHP - Sort an array by category I want [duplicate]PHP - 按我想要的类别对数组进行排序[重复]
【发布时间】:2021-08-04 13:47:50
【问题描述】:

我需要按衣服尺寸对数组进行排序,如下例所示。

我需要从 :['M', 'M', 'S', 'XL', 'L', 'XL', 'S', 'M', 'XL', 'S']

并到达:['S', 'S', 'S', 'M', 'M', 'M', 'L', 'XL', 'XL', 'XL']

这就是我所做的。它有效,但我不喜欢它,它似乎没有优化。我希望我只有一个 foreach

function trier(array $table):array{
    $tableauVide=[];

         foreach($table as $element){
        if($element=='S'){
        array_push($tableauVide,$element);
        }
    }
         foreach($table as $element){
        if($element=='M'){
        array_push($tableauVide,$element);
        }
    }
      foreach($table as $element){
        if($element=='L'){
        array_push($tableauVide,$element);
        }
    }
    foreach($table as $element){
        if($element=='XL'){
        array_push($tableauVide,$element);
        }
    }

return $tableauVide; }
 var_dump(trier(['M', 'M', 'S', 'XL', 'L', 'XL', 'S', 'M', 'XL', 'S']));

我是 PHP 新手,所以我阅读了很多东西来对数组进行排序。就像函数 usort( 似乎这是将数组排序为特定方式的方法,但我不知道它是如何工作的。你能给我一个提示吗?或者你将如何处理以使其更好?

谢谢

【问题讨论】:

  • 你没有多维数组,但是原理是一样的。适应自己的情况应该不会太难。

标签: php arrays sorting


【解决方案1】:
function trier(array $table): array {
  // User-defined sorting callback function will use this array to compare sizes based on their index in this array.
  $correctOrderOfSizes = ['XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL'];

  // `usort` accepts a callback function, which does the custom comparison between 2 items.
  // `array_search` returns the index of a given element in an array, values which we will compare (e.g. index for 'S' is 2 and index for 'L' is 4, so we will compare 2 with 4).
  // `<=>` is called the spaceship operator (https://www.php.net/manual/en/language.operators.comparison.php)
  usort($table, function($a, $b) use ($correctOrderOfSizes) {
      return array_search($a, $correctOrderOfSizes) <=> array_search($b, $correctOrderOfSizes);
  });
  return $table;
}

var_dump(trier(['M', 'M', 'S', 'XL', 'L', 'XL', 'S', 'M', 'XL', 'S']));
  • 注意:上述代码无法(正确)处理使用“未知”尺寸的情况。

【讨论】:

  • 非常感谢,我需要努力!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-19
  • 2011-12-02
  • 2012-06-23
  • 2013-07-26
  • 2011-05-29
相关资源
最近更新 更多