如何在 PHP 上对键不是字符串标签的多维数组进行排序 [英] How to sort a multidimensional array on PHP where keys are not string labels

查看:33
本文介绍了如何在 PHP 上对键不是字符串标签的多维数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个多维数组:

$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] 元素上对数组进行排序.这不起作用:

But I am unable to sort the array on the [0] element. This does not work:

array_multisort( $serviceTimes[0], SORT_ASC, $serviceTimes );

这也不行

array_multisort( $serviceTimes[][0], SORT_ASC, $serviceTimes );

有什么想法吗?

理想和最终,这就是我想要制作的:

Ideally and ultimately, this is what I am looking to produce:

Array (
  [0] => 2:15pm )
  [1] => 7:00pm )
  [2] => 7:00pm )
  [3] => 7:19pm )
  [4] => 8:20pm )
)

推荐答案

使用 array_column 从子数组中提取 0 列并对其进行排序:

Use array_column to extract the 0 column from the sub-arrays and sort on that:

array_multisort(array_column($serviceTimes, 0), SORT_ASC, $serviceTimes);

您声明对 0 元素进行排序,但您的输出显示来自 1 元素的时间.如果是这样,只需将 array_column 参数更改为 1.

You state sorting on the 0 element but your output shows times from the 1 element. If so just change the array_column argument to a 1.

这篇关于如何在 PHP 上对键不是字符串标签的多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆