Sorting multidimensional array based on the order of plain array

后端 未结 5 1078
时光说笑
时光说笑 2021-01-28 11:06

I have this array:

  $routes = array(
  array(
     \'code\' => \'PZSA\',
     \'name\' => \'PLaza san antonio\',
  ),
  array(
     \'code\' => \'AVAD\         


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-01-28 11:56

    A little more generic solution where you can just set the key you wish to sort by and it should work for any multidimensional array.

    //key to sort by
    $sortBy = 'code';
    
    $sorted = array();
    foreach($routes as $route) {
      foreach($route as $key => $value) {
        if(!isset($sorted[$key])) {
          $sorted[$key] = array();
        }
        $sorted[$key][] = $value;
      }
    }
    
    array_multisort($sorted[$sortBy], SORT_ASC, $routes); 
    print_r($routes)
    

提交回复
热议问题