PHP - 使用 array_multisort 对多维数组进行排序
PHP - sorting multidimensional array using array_multisort
我有这个多维数组
Array
(
[0] => Array
(
[at] => 0
[bt] => 9
)
[1] => Array
(
[at] => 3
[bt] => 5
)
[2] => Array
(
[at] => 0
[bt] => 3
)
)
我想按“at”键对其进行排序,所以我尝试了这段代码
//$process = array() given above
$p = array();
foreach ($process as $key => $row) {
$p[$key] = $row['at'];
}
array_multisort($p, SORT_NUMERIC, SORT_ASC, $process);
我得到了这个结果
Array
(
[0] => Array
(
[at] => 0
[bt] => 3
)
[1] => Array
(
[at] => 0
[bt] => 9
)
[2] => Array
(
[at] => 3
[bt] => 5
)
)
它对“at”进行排序,但它也对“bt”进行排序。
如何仅按“at”键对数组进行排序?
像这样:
Array
(
[0] => Array
(
[at] => 0
[bt] => 9
)
[1] => Array
(
[at] => 0
[bt] => 3
)
[2] => Array
(
[at] => 3
[bt] => 5
)
)
谢谢。
编辑:
至于callmemath下面的回答
当我的阵列上只有这个时,
Array
(
[0] => Array
(
[at] => 0
[bt] => 9
)
[1] => Array
(
[at] => 0
[bt] => 3
)
)
如何防止它排序,因为我只想按“at”键对其进行排序。没有什么可排序的,因为它们都是 0。
使用usort:
$array = array(
array('at' => 0, 'bt' => 9),
array('at' => 3, 'bt' => 5),
array('at' => 0, 'bt' => 3)
);
usort($array, function($a, $b) {
return $a['at'] - $b['at'];
});
var_dump($array);
我有这个多维数组
Array
(
[0] => Array
(
[at] => 0
[bt] => 9
)
[1] => Array
(
[at] => 3
[bt] => 5
)
[2] => Array
(
[at] => 0
[bt] => 3
)
)
我想按“at”键对其进行排序,所以我尝试了这段代码
//$process = array() given above
$p = array();
foreach ($process as $key => $row) {
$p[$key] = $row['at'];
}
array_multisort($p, SORT_NUMERIC, SORT_ASC, $process);
我得到了这个结果
Array
(
[0] => Array
(
[at] => 0
[bt] => 3
)
[1] => Array
(
[at] => 0
[bt] => 9
)
[2] => Array
(
[at] => 3
[bt] => 5
)
)
它对“at”进行排序,但它也对“bt”进行排序。
如何仅按“at”键对数组进行排序?
像这样:
Array
(
[0] => Array
(
[at] => 0
[bt] => 9
)
[1] => Array
(
[at] => 0
[bt] => 3
)
[2] => Array
(
[at] => 3
[bt] => 5
)
)
谢谢。
编辑:
至于callmemath下面的回答
当我的阵列上只有这个时,
Array
(
[0] => Array
(
[at] => 0
[bt] => 9
)
[1] => Array
(
[at] => 0
[bt] => 3
)
)
如何防止它排序,因为我只想按“at”键对其进行排序。没有什么可排序的,因为它们都是 0。
使用usort:
$array = array(
array('at' => 0, 'bt' => 9),
array('at' => 3, 'bt' => 5),
array('at' => 0, 'bt' => 3)
);
usort($array, function($a, $b) {
return $a['at'] - $b['at'];
});
var_dump($array);