我正在用PHP进行多维数组排序。我想根据lineNumber对数组进行排序,从而对公交路线进行排序(即Tasen,Ekeberg Hageby和Jernbanetorget。我的数组如下:
Array (
[Ryenbergveien] => Array
(
[Tasen] => Array
(
[lineNumber] => 34
[expectedMinutes] => Array
(
[0] => 0
[1] => 15
[2] => 30
)
)
[Ekeberg hageby] => Array
(
[lineNumber] => 84
[expectedMinutes] => Array
(
[0] => 6
[1] => 20
[2] => 35
)
)
[Jernbanetorget] => Array
(
[lineNumber] => 74
[expectedMinutes] => Array
(
[0] => 7
[1] => 22
[2] => 37
[3] => 52
)
)
)
我希望相对于lineNumber以升序在总线路线级别(Tasen,Jernbanetorget和Ekeberg hageby)对数组进行排序,例如:
Array (
[Ryenbergveien] => Array
(
[Tasen] => Array
(
[lineNumber] => 34
[expectedMinutes] => Array
(
[0] => 0
[1] => 15
[2] => 30
)
)
[Jernbanetorget] => Array
(
[lineNumber] => 74
[expectedMinutes] => Array
(
[0] => 7
[1] => 22
[2] => 37
[3] => 52
)
)
[Ekeberg hageby] => Array
(
[lineNumber] => 84
[expectedMinutes] => Array
(
[0] => 6
[1] => 20
[2] => 35
)
)
)
谢谢!
编辑:已解决,感谢:https://stackoverflow.com/a/48529086/7009817 解决方案:
function multisortByKeyValue( $k, $arr ) {
$ids = array();
$index = 1;
foreach ( $arr as $key => $row ) {
$ids[ $key ] = intval( $row[ $k ] ) . '-' . $index . '-' . $key;
$index ++;
}
natsort( $ids );
$arr = array_merge( $ids, $arr );
return $arr;
}
foreach ( $bussline as $a1 => $verdi ) { // loop gjennom hver holdeplass
foreach ( $bussline[$a1] as $a2 => $verdi ) { // loop gjennom hver bussrute
$bussline[$a1] = multisortByKeyValue( 'linje', $bussline[$a1] );
}
}