php - How to sort an array like this? Any advice?
怪我咯
怪我咯 2017-05-16 13:07:13
0
6
370

**

按照content2排序

**

array(5) {
  [0]=>
  array(2) {
    ["id"]=>
    string(1) "2"
    ["content2"]=>
    string(2) "XL"
  }
  [1]=>
  array(2) {
    ["id"]=>
    string(1) "1"
    ["content2"]=>
    string(1) "L"
  }
  [2]=>
  array(2) {
    ["id"]=>
    string(1) "3"
    ["content2"]=>
    string(3) "XXL"
  }
  [3]=>
  array(2) {
    ["id"]=>
    string(1) "4"
    ["content2"]=>
    string(1) "L"
  }
  [4]=>
  array(2) {
    ["id"]=>
    string(1) "5"
    ["content2"]=>
    string(2) "XL"
  }
}
怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(6)
阿神

PHP multidimensional array sorting array

/**
* Sort array by filed and type, common utility method.
* @param array $data
* @param string $sort_filed
* @param string $sort_type SORT_ASC or SORT_DESC
*/
public function sortByOneField($data, $filed, $type)
{
    if (count($data) <= 0) {
        return $data;
    }
    foreach ($data as $key => $value) {
        $temp[$key] = $value[$filed];
    }
    array_multisort($temp, $type, $data);
    return $data;
}
習慣沉默
 $list = [
    ['id'=>1,'content1'=>'L'],
    ['id'=>2,'content1'=>'XL'],
    ['id'=>3,'content1'=>'XXL'],
    ['id'=>4,'content1'=>'M'],
    ['id'=>5,'content1'=>'LM'],
    ['id'=>6,'content1'=>'XXXL'],
];
    foreach ($list as $key => $value) {
        $data[$key] = $value['content1'];
    }

    array_multisort($data, SORT_ASC, $list);
    var_dump($list);
刘奇

There is no regular pattern in clothing sizes, right? Should they be numbered in a certain order when inserted into the library and then sorted when taken out

刘奇

Just write a bubble sort.
As for L<XL<XXL<XXL, just set up a map mapping for comparison.

You can also use usort to customize the sorting logic. Reference:

http://php.net/manual/zh/func...

小葫芦
<?php 
$list = [
    ['id'=>1,'content'=>'L'],
    ['id'=>2,'content'=>'XL'],
    ['id'=>3,'content'=>'XXL'],
    ['id'=>4,'content'=>'M'],
    ['id'=>5,'content'=>'LM'],
    ['id'=>6,'content'=>'XXXL'],
];

$size = [
    'XXXL' => 1,
    'XXL' => 2,
    'XL' => 3,
    'L' => 4,
    'M' => 5,
    'LM' => 6,
];

$temp = array();
foreach ($list as $key => $val) {
    $temp[$size[$val['content']]] = $val;
}
// print_r($temp);die;

ksort($temp); // 从低到高  krsort 从高到低
print_r($temp);
?>

I just wrote it casually, not sure if this is what you want.

淡淡烟草味
$arr = [
    ["id" => "1", "content" => 'XL' ],
    ["id" => "2", "content" => 'L'],
    ["id" => "3", "content" => 'XXL' ],
];

$rules = ['L'=>1, 'XL'=>2, 'XXL'=>3];

usort($arr, function($a, $b) use ($rules) {
    return $rules[$a['content']] <=> $rules[$b['content']];
});

var_dump($arr);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template