我有这个多维数组:
$serviceTimes = Array (
[0] => Array ( [0] => PM1900 [1] => 7:00pm )
[1] => Array ( [0] => PM1900 [1] => 7:00pm )
[2] => Array ( [0] => PM1415 [1] => 2:15pm )
[3] => Array ( [0] => PM1919 [1] => 7:19pm )
[6] => Array ( [0] => PM2020 [1] => 8:20pm )
)
但是我无法对[0]元素上的数组进行排序。这不起作用:
array_multisort( $serviceTimes[0], SORT_ASC, $serviceTimes );
这也不起作用
array_multisort( $serviceTimes[][0], SORT_ASC, $serviceTimes );
有什么想法吗?
理想情况下,最终,这就是我要制作的内容:
Array (
[0] => 2:15pm )
[1] => 7:00pm )
[2] => 7:00pm )
[3] => 7:19pm )
[4] => 8:20pm )
)
答案 0 :(得分:4)
使用array_column
从子数组中提取0
列并对其进行排序:
array_multisort(array_column($serviceTimes, 0), SORT_ASC, $serviceTimes);
您说明0
元素的排序,但您的输出显示1
元素的时间。如果是这样,只需将array_column
参数更改为1
。
答案 1 :(得分:1)
通常,您也可以将usort()与自己的compoare函数一起用于此类自定义排序(所有函数前缀为" u":usort,{{3 },uasort ...)
<?php
function mysort ($a, $b){
return strcmp($a[0], $b[0]);
}
$serviceTimes = array ( 0 => array ( 0 => 'PM1900', 1 => '7:00pm', ), 1 => array ( 0 => 'PM1900', 1 => '7:00pm', ), 2 => array ( 0 => 'PM1415', 1 => '2:15pm', ), 3 => array ( 0 => 'PM1919', 1 => '7:19pm', ), 4 => array ( 0 => 'PM2020', 1 => '8:20pm', ), );
usort($serviceTimes, 'mysort');
var_dump(serviceTimes);