PHP sort array alphabetically using a subarray value

05/07/2020 01:00:02

Possible Duplicate:
How can I sort arrays and data in PHP?
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?

Verified Answer (145 Votes)

05/07/2012 20:34:29

Here is your answer and it works 100%, I've tested it.

<?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);
145

Answer #2 (16 Votes)

05/07/2012 20:22:18

usort is your friend:

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

usort($array, "cmp");
16
2
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.