Possible Duplicate:
How do I sort a multidimensional array in php
PHP Sort Array By SubArray Value
PHP sort multidimensional array by value

My array looks like:

Array(
    [0] => Array(
         [name] => Bill
         [age] => 15
    ),
    [1] => Array(
         [name] => Nina
         [age] => 21
    ),
    [2] => Array(
         [name] => Peter
         [age] => 17
    )
);

I would like to sort them in alphabetic order based on their name. I saw PHP Sort Array By SubArray Value but it didn't help much. Any ideas how to do this?

share|improve this question
2  
The question you linked contains the exact answer you need.. just replace 'optionNumber' with 'name' in the comparison function. Voting to close as duplicate. If there's something in the other question you don't understand please ask specifically about that. – Mike B May 7 '12 at 15:21
I've never seen an array that has the same key for two values. Probably that's why the sort does not work? – hakre May 7 '12 at 15:29

marked as duplicate by Mike B, hakre, Madara Uchiha, Matt, outis Jun 14 '12 at 7:50

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

up vote 2 down vote accepted

Here is your answer and it works 100%, I've tested it: http://marianzburlea.com/sort-multidimensional-array-values-name

<?php
$a = Array(
    1 => Array(
         'name' => 'Peter',
         'age' => 17
    ),
    0 => Array(
         'name' => 'Nina',
         'age' => 21
    ),
    2 => Array(
         'name' => 'Bill',
         'age' => 15
    ),
);
function compareByName($a, $b) {
  return strcmp($a["name"], $b["name"]);
}
usort($a, 'compareByName');
/* The next line is used for debugging, comment or delete it after testing */
print_r($a);
share|improve this answer

usort is your friend:

function cmp($a, $b)
{
        return strcmp($a["name"], $b["name"]);
}

usort($array, "cmp");
share|improve this answer

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