Heim > Fragen und Antworten > Hauptteil
**
**
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"
}
}
阿神2017-05-16 13:09:13
PHP多维数组排序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;
}
習慣沉默2017-05-16 13:09:13
$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);
怪我咯2017-05-16 13:09:13
写个冒泡排序不就得了。
至于 L<XL<XXL<XXL 这种,设置一个 map 映射来比较就是。
也可以用 usort
来自定义排序逻辑。参考:
http://php.net/manual/zh/func...
高洛峰2017-05-16 13:09:13
<?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);
?>
随便写了一下,不知道你要的是不是这个样子。
淡淡烟草味2017-05-16 13:09:13
$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);