如何在PHP上对多维数组进行排序,其中键不是字符串标签

时间:2017-12-08 16:35:13

标签: php multidimensional-array

我有这个多维数组:

$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 )
)

2 个答案:

答案 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);