登录后台

页面导航

本文编写于 214 天前,最后修改于 214 天前,其中某些信息可能已经过时。

php二维数组,多字段排序

需求背景:
返回一个充值列表要求:

  • 有首充字段的充值档位放在前面
  • 充值档位按照从低到高的顺序排列

原始数据:

   //firstCharge 首充字段
   //price 充值价格 
    
   $array = [
              [
                  'firstCharge' => 1,
                  'price' => 100,
              ],
              [
                  'firstCharge' => 1,
                  'price' => 150,
              ],
              [
                  'firstCharge' => 0,
                  'price' => 200,
              ],
              [
                  'firstCharge' => 0,
                  'price' => 100,
              ],
              [
                  'firstCharge' => 0,
                  'price' => 499,
              ],
              [
                  'firstCharge' => 1,
                  'price' => 255,
              ],
          ];   
          
          
   $firstCharge = array_column($array, 'firstCharge');
   $price = array_column($array, 'price');
   array_multisort($firstCharge, SORT_DESC, $price, SORT_ASC, $array);
   
   $array = [
               [
                   "firstCharge" => 1,
                   "price"       => 100
               ],
               [
                   "firstCharge" => 1,
                   "price"       => 150
               ],
               [
                   "firstCharge" => 1,
                   "price"       => 255
               ],
               [
                   "firstCharge" => 0,
                   "price"       => 100
               ],
               [
                   "firstCharge" => 0,
                   "price"       => 200
               ],
               [
                   "firstCharge" => 0,
                   "price"       => 499
               ]
           ];
            

这里用到了php函数array_multisort ,可以用来一次对多个数组进行排序,或者根据某一维或多维对多维数组进行排序。

已有 1 条评论