php多维按字符串排序

时间:2017-01-04 07:28:45

标签: php sorting

我想使用php以降序排序数组。

喜欢'XXS','XS','S','M','L','XL','2X','3X','4X','5X','6','7','8','9','10','11'

$attributesData['attributes'][$key]['options'][$search]这将返回以下数组值,并将其存储到$data['attributes'][$key]此数组之前,我希望在label数组中按$data['attributes'][$key]排序。

Array
(
    [id] => 68
    [label] => 2X
)
Array
(
    [id] => 69
    [label] => 3X

)
Array
(
    [id] => 72
    [label] => L
)
Array
(
    [id] => 73
    [label] => M
)

我尝试了许多方法,但没有得到适当的解决方案。

4 个答案:

答案 0 :(得分:3)

您可以使用usort执行此操作:

$sizes = ['XXS' => 16, 'XS' => 15, 'S' => 14, 'M' => 13, 'L' => 12, 'XL' => 11, '2X' => 10, '3X' => 9, '4X' => 8, '5X' => 7, '6' => 6, '7' => 5, '8' => 4, '9' => 3, '10' => 2, '11' => 1];

usort($myArray, function($a, $b) use ($sizes) {
    if ($a['label'] == $b['label']) {
        return 0;
    }

    return $sizes[$a['label']] < $sizes[$b['label']] ? -1 : 1;
});

var_dump($myArray);

答案 1 :(得分:1)

你可以试试这个。它应该以{{1​​}}中定义的任何顺序排序

array

<强>输出

// Array of labels in order
$order = ['XXS','XS','S','M','L','XL','2X','3X','4X','5X','6','7','8','9','10','11'];
// values
$array =[
[
    'id' => 68,
    'label' => '2X',
],
[
    'id' => 69,
    'label' => '3X',

],
[
    'id' => 72,
    'label' => 'L',
],
[
    'id' => 73,
    'label' => 'M',
]];

$new = [];
foreach($order as $o) {
   // Get the index of the label in values
   $pos = array_search($o, array_column($array, 'label'));
   // If found store in new array
   if($pos !== false) {
      $new[] = $array[$pos];
   }
}

var_dump($new);

Demo

答案 2 :(得分:1)

使用usort对它们进行排序。

$size = ['XXS','XS','S','M','L','XL','2X','3X','4X','5X','6','7','8','9','10','11'];
$weight = array_flip($size);
$result = usort($sortSize, function($a, $b) use($weight){return $weight[$b['label']] > $weights[$a['label']];});

答案 3 :(得分:0)

认为这可能有效

    <?php

$a = Array(
    1 => Array(
         'id' => 68,
         'label' => '2X'
    ),
    0 => Array(
         'id' => 69,
         'label' => '3X'
    ),
    2 => Array(
         'id' => 70,
         'label' => 'L'
    ),
     3 => Array(
         'id' => 71,
         'label' => 'XXS'
    ),
    4 => Array(
         'id' => 72,
         'label' => '11'
    ),
    5 => Array(
         'id' => 72,
         'label' => 'M'
    ),
);
function compareByName($a, $b) {
  return strcmp($a["label"], $b["label"]);
}
usort($a, 'compareByName');
print_r(array_reverse($a)); ?>

DEMO