Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

How to sort a multidimensional array on PHP where keys are not string labels

I have this 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 )
)

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

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

nor does this work

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

Any thoughts?

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 )
)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...