简体   繁体   中英

php sort arrays in an array alphabetically on a value

I have an array containing more arrays of state information. One of the key val pairs is the name of the state, which I would like to sort such that the outter array of states contains all of the state arrays sorted alphabetically by the name.

Thanks!

Use the usort function . It allows providing a callback used to compare the elements of the array to sort. This callback, in your case, would extract the state names from the two inner arrays to compare, and compare the names.

If the structure of your array is the folowing:

<?php
$states = array(
  'spain'=>array('population' => '46,030,109', 'capital' => 'Madrid'),
  'italy'=>array('population' => '60,681,514', 'capital' => 'Rome'),
  'germany'=>array('population' => '81,799,600', 'capital' => 'Berlin'));

you can use ksort .

Codepad example

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