简体   繁体   中英

How to sort by key within multidimensional array

I made this fictional membership list. I'd like to maintain the order of the sub arrays (class year) while sorting by descending key within each sub array.

$pledges = array(
  'smith'     => "Joe Patterson",
  'jones'     => "Robert Nelson",
  'davis'     => "Jimmy Davis",
  'carpenter' => "Mike Carpenter");

$sophomores = array(
  'ford'      => "Kevin Ford",
  'gomez'     => "Pedro Gomez",
  'miller'    => "Jack Miller",
  'pullman'   => "Lucas Pullman");

$juniors = array(
  'bradford'  => "Nicholas Bradford",
  'daniels'   => "Robert Daniels",
  'soren'     => "Jon Soren",
  'cooper'    => "Harrison Cooper");

$seniors = array(
  'mcdonald'  => "Casey McDonald",
  'witten'    => "Tim Witten",
  'session'   => "Benjamin Sessions",
  'redding'   => "Jack Redding");

How do I do that? Thanks a bunch.

The PHP manual has a good example of what you're looking to do.

http://www.php.net/manual/en/function.ksort.php#98465

by using ksort function of PHP you can sort array key wise.

ksort($pledges);
array_reverse($pledges);
and like wise for others....

what you have posted is single dimension array and be aware that ksort will be only applicable to single dimension array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM