-1

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!

Hippocrates
  • 2,510
  • 1
  • 19
  • 35
  • possible duplicate of [PHP Sort Array By SubArray Value](http://stackoverflow.com/questions/2477496/php-sort-array-by-subarray-value) and many more. – Evan Mulawski Nov 05 '11 at 22:08

2 Answers2

3

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • +1 For usort, this will work well. However, @Hippocrates if your data set is quite large it may be worthwhile looking into array_multisort as the function calls can make usort resource heavy on large data sets. – majic bunnie Nov 05 '11 at 22:25
0

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

Benjamin Crouzier
  • 40,265
  • 44
  • 171
  • 236