php - 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( 似乎这就是将数组排序为特定方式的方法,但我不知道它是如何工作的。你能给我一个提示吗?或者你将如何处理以使其更好?
谢谢
解决方案
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']));
- 注意:上面的代码不能(正确地)处理使用“未知”大小的情况。
推荐阅读
- reactjs - 在渲染中显示数组映射
- node.js - 节点/HAPI:同时连接太多导致网络连接被重置
- c++ - 如何将windows-936写入日志当wchar_t在代码中通过boost.log
- windows - 如何在 CMD 中调用 %random% 与以前的 %random% 相同?
- javascript - 我的 Ajax 函数发出双重请求
- r - 指数衰减适合 r
- visual-studio-2017 - 为什么 Visual Studio 在运行测试之前不复制静态文件?
- java - Vertx 将 zip 文件流式传输到 http 响应
- java - 解析由 | 分隔的单词
- c++ - 在 C++ 中使用扁平数组语法,崩溃取决于宽度/高度