天天看點

php二維數組多個字段排序,PHP的二維數組多字段排序

該樓層疑似違規已被系統折疊 隐藏此樓檢視此樓

1. 起因今天一個學生問的對二維數組排序的問題。 例如: 當年齡相同時,再按照身高逆序排序。

$datas = [

['age' => 67, 'height' => 2],

['age' => 86, 'height' => 1],

['age' => 85, 'height' => 6],

['age' => 98, 'height' => 2],

['age' => 86, 'height' => 6],

['age' => 67, 'height' => 7]

];

第一時間想到array_multisort, 但是很遺憾的時預設情況下都是升序排列。

$datas = [

['age' => 67, 'height' => 2],

['age' => 86, 'height' => 7],

['age' => 85, 'height' => 6],

['age' => 98, 'height' => 2],

['age' => 86, 'height' => 6],

['age' => 67, 'height' => 7]

];

array_multisort($datas);

echo "

";      

print_r($datas);

exit;

得到的結果是:

Array

(

[0] => Array

(

[age] => 67

[height] => 2

)

[1] => Array

(

[age] => 67

[height] => 7

)

[2] => Array

(

[age] => 85

[height] => 6

)

[3] => Array

(

[age] => 86

[height] => 6

)

[4] => Array

(

[age] => 86

[height] => 7

)

[5] => Array

(

[age] => 98

[height] => 2

)

)

2. 如何解決這個問題呢?

function array_multisort_orderby()

{

$args = func_get_args();

$data = array_shift($args);

foreach ($args as $n => $field) {

if (is_string($field)) {

$tmp = array();

foreach ($data as $key => $row)

$tmp[$key] = $row[$field];

$args[$n] = $tmp;

}

}

$args[] = &$data;

call_user_func_array('array_multisort', $args);

return array_pop($args);

}

$datas = [

['age' => 67, 'height' => 2],

['age' => 86, 'height' => 7],

['age' => 85, 'height' => 6],

['age' => 98, 'height' => 2],

['age' => 86, 'height' => 6],

['age' => 67, 'height' => 7]

];

$sorted = array_multisort_orderby($datas, 'age',SORT_ASC , 'height', SORT_DESC);

echo "

";      

var_dump($sorted);

本文由源碼時代PHP教育訓練學科講師原創出品