This article mainly introduces PHP two-dimensional array sorting by key value, which has certain reference value. Now I share it with everyone. Friends in need can refer to it
Source: http:// www.jb51.net/article/43787.htm
array_multisort() in PHP can be used to sort multiple arrays at one time, or to sort multi-dimensional arrays according to a certain dimension or multiple dimensions. Sort. The associated key names remain unchanged, but the numeric key names are re-indexed. The input arrays are treated as columns of a table and sorted by rows, with the first array being the main array to be sorted. If the rows (values) in the array are compared to be the same, they are sorted according to the size of the corresponding value in the next input array, and so on.
But if the array that needs to be sorted is a two-dimensional array, it needs to be sorted according to the key value of the array. For example, the two-dimensional array below needs to be sorted according to the sort key name, then array_multisort() cannot be implemented directly. :
#[php] view plain copy
##
$data[5] = array('volume' => 67, 'edition' => 2); $data[4] = array('volume' => 86, 'edition' => 1); $data[2] = array('volume' => 85, 'edition' => 6); $data[3] = array('volume' => 98, 'edition' => 2); $data[1] = array('volume' => 86, 'edition' => 6); $data[6] = array('volume' => 67, 'edition' => 7); // 准备要排序的数组 foreach ($data as $k => $v) { $edition[] = $v['edition']; } array_multisort($edition, SORT_ASC, $data); print_r($data);
copy
<span style="font-family:tahoma, arial, '宋体';"><span style="font-size:14px;line-height:20px;">Array ( [0] => Array ( [volume] => 86 [edition] => 1 ) [1] => Array ( [volume] => 67 [edition] => 2 ) [2] => Array ( [volume] => 98 [edition] => 2 ) [3] => Array ( [volume] => 85 [edition] => 6 ) [4] => Array ( [volume] => 86 [edition] => 6 ) [5] => Array ( [volume] => 67 [edition] => 7 ) </span></span> )
Other cases: http://www.cnblogs.com/dragonbad/p/ 6184568.html
$arr=[ array( 'name'=>'小坏龙', 'age'=>28 ), array( 'name'=>'小坏龙2', 'age'=>14 ), array( 'name'=>'小坏龙3', 'age'=>59 ), array( 'name'=>'小坏龙4', 'age'=>23 ), array( 'name'=>'小坏龙5', 'age'=>23 ), array( 'name'=>'小坏龙6', 'age'=>21 ), ];
array_multisort(array_column($arr,'age'),SORT_DESC,$arr);
print_r($arr);
其中 array_column(数组,数组中的某个键值) 从多维数组中取出某个键值的一列 返回一个一维数组;
array_multisort(数组(一维数组),排序方式(SOTR_ASC,SOTR_DESC),其他数组(可以是二维的))
相关推荐:
The above is the detailed content of PHP two-dimensional array sorted by key value. For more information, please follow other related articles on the PHP Chinese website!