首页 > 解决方案 > PHP - 按我想要的类别对数组进行排序

问题描述

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

我需要从:['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( 似乎这就是将数组排序为特定方式的方法,但我不知道它是如何工作的。你能给我一个提示吗?或者你将如何处理以使其更好?

谢谢

标签: phparrayssorting

解决方案


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']));
  • 注意:上面的代码不能(正确地)处理使用“未知”大小的情况。

推荐阅读