sort a multidimensional array using array_multisort

后端 未结 4 1282
感情败类
感情败类 2020-12-17 17:07

I have this array

Array
(
    [0] => Array
        (
            [brand] => blah blah
            [location] => blah blah
            [address] =>         


        
相关标签:
4条回答
  • 2020-12-17 17:33

    You need to extract all the distances first, then pass both the distance and the data to the function. As shown in example 3 in the array_multisort documentation.

    foreach ($data as $key => $row) {
        $distance[$key] = $row['distance'];
    }
    
    array_multisort($distance, SORT_ASC, $data);
    

    This assumes you want the shortest distances first, otherwise change the SORT_ASC to SORT_DESC

    0 讨论(0)
  • 2020-12-17 17:42

    If you want to avoid the looping you can use the array_column function to achieve your target. For Example,

    You want to sort below array with distance sort

    $arr = array( 
      0 => array( 'lat' => 34, 'distance' => 332.08 ),
      1 => array( 'lat' => 34, 'distance' => 5 ),
      2 => array( 'lat' => 34, 'distance' => 34 )
    );
    

    Using below single line your array will be sort by distance

    array_multisort( array_column( $arr, 'distance' ), SORT_ASC, SORT_NUMERIC, $arr );
    

    Now, $arr contain with sorted array by distance

    0 讨论(0)
  • 2020-12-17 17:54

    Use can use usort;

    function cmpDistance($a, $b) {
        return ($a['distance'] - $b['distance']);
    }
    
    usort($array, "cmpDistance");
    
    0 讨论(0)
  • 2020-12-17 17:56

    This code helps to sort the multidimensional array using array_multisort()

      $param_dt = array();
      foreach ($data_set as $key => $row) {
         if(isset($row['params']['priority']))
         {
           $param_dt[$key] = $row['params']['priority'];
         }
         else
         {
            $param_dt[$key] = -2; // if priority key is not set for this array - it first out
         }
        }
    
      array_multisort($param_dt, SORT_ASC,SORT_NUMERIC, $data_set); 
    

    Now $data_set has the sorted list of elements.

    0 讨论(0)
提交回复
热议问题