0

I need to sort an array by clothes size like in the exemple below.

I need to start from :['M', 'M', 'S', 'XL', 'L', 'XL', 'S', 'M', 'XL', 'S']

and arrive to : ['S', 'S', 'S', 'M', 'M', 'M', 'L', 'XL', 'XL', 'XL']

Here you are what i did. It works but I dont like it , it doesnt seems optimize. I wish i have only one 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']));

I'm new to PHP , so i have read a lot of stuff to sort an array. Like the function usort( it seems thats the way to sort an array to a specific way but i can't figure out how it works. may you give me a hint with it ? or how would you process to make it better ?

Thanks

8uld0zr
  • 69
  • 1
  • 7
  • You don't have a multidimensional array, but the principle is identical. Shouldn't be too hard to adapt to your own situation. – El_Vanja May 14 '21 at 11:33

1 Answers1

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']));
  • Note: The above code does not handle (correctly) cases when an "unknown" size is used.
Zoli Szabó
  • 4,366
  • 1
  • 13
  • 19