Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
possible duplicate of PHP Sort Array By SubArray Value and many more. – Evan Mulawski Nov 5 '11 at 22:08

2 Answers

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.

share|improve this answer
+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 5 '11 at 22:25

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.