如何对这样的数组进行排序 求教

痴情笑我凡俗
  • 348

**

按照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"
  }
}
回复
阅读 2.6k
6 个回答
stephenhuang
  • 109
✓ 已被采纳

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;
}
痴情笑我凡俗
  • 348
 $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);

衣服尺码没什么规律吧 是不是应该在插入库里的时候按照某种特定顺序编号 取出来的时候再排序

任侠
  • 253

写个冒泡排序不就得了。
至于 L<XL<XXL<XXL 这种,设置一个 map 映射来比较就是。

也可以用 usort 来自定义排序逻辑。参考:

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);
?>

随便写了一下,不知道你要的是不是这个样子。

$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);
宣传栏