简体   繁体   English

按列中的值对多维数组进行排序

[英]Sort a multidimensional array by values in a column

I have this array我有这个数组

Array
(
    [0] => Array
        (
            [brand] => blah blah
            [location] => blah blah
            [address] => blah blah
            [city] => blah blah
            [state] => CA
            [zip] => 90210
            [country] => USA
            [phone] => 555-1212
            [long] => -111
            [lat] => 34
            [distance] => 3.08
        )
    [1] => Array
        (
            [brand] => blah blah
            [location] => blah blah
            [address] => blah blah
            [city] => blah blah
            [state] => CA
            [zip] => 90210
            [country] => USA
            [phone] => 555-1212
            [long] => -111
            [lat] => 34
            [distance] => 5
        )
.
.
.

}

I want to be able to sort the arrays in the hash by distance.我希望能够按距离对散列中的数组进行排序。

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.array_multisort文档中的示例 3 所示。

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这假设您首先想要最短距离,否则将SORT_ASC更改为SORT_DESC

If you want to avoid the looping you can use the array_column function to achieve your target.如果你想避免循环,你可以使用array_column函数来实现你的目标。 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现在, $arr包含距离排序的数组

Use can use usort ;使用可以使用usort

function cmpDistance($a, $b) {
    return ($a['distance'] - $b['distance']);
}

usort($array, "cmpDistance");

This code helps to sort the multidimensional array using array_multisort()此代码有助于使用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.现在$data_set有元素的排序列表。

We have an array of rows, but array_multisort() requires an array of columns, so we use the below code to obtain the columns, then perform the sorting.我们有一个行数组,但是 array_multisort() 需要一个列数组,所以我们使用下面的代码来获取列,然后执行排序。

// as of PHP 5.5.0 you can use array_column() instead of the above code
$brand= array_column($data, 'brand');
$city= array_column($data, 'city');

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($brand, SORT_DESC, $city, SORT_ASC, $data);

The advantage to calling usort() instead of array_multisort() , is that you don't need to pre-iterate the input array to generate an array of columnar data.调用usort()而不是array_multisort()的优点是您不需要预先迭代输入数组来生成列数据数组。

The following one-liner will use PHP7.4's arrow function syntax with PHP7's "spaceship operator" / "three-way comparison operator" to sort the input array (by reference) based on the distance column values.下面的单行将使用PHP7.4的箭头函数语法和PHP7的“飞船操作符”/“三向比较操作符”根据距离列值对输入数组(按引用)进行排序。

With $a on the left side of <=> and $b on the right side, ascending order is used.随着$a对左侧<=>$b右侧,使用升序。 To achieve descending sorting, write $b['distance'] <=> $a['distance'] .要实现降序排序,请编写$b['distance'] <=> $a['distance']

Code:代码:

usort($array, fn($a, $b) => $a['distance'] <=> $b['distance']);

var_export($array);

To break ties while sorting, you can declare multiple values to sort on via arrays of values.要在排序时打破关系,您可以声明多个值以通过值数组进行排序。

The following will sort by:以下将按以下顺序排序:

  1. distance ASC then距离 ASC 然后
  2. country DESC then国家 DESC 然后
  3. state ASC then状态 ASC 然后
  4. city ASC城市ASC

Code:代码:

usort(
    $array,
    fn($a, $b) =>
        [$a['distance'], $b['country'], $a['state'], $a['city']]
        <=>
        [$b['distance'], $a['country'], $b['state'], $b['city']]
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM