PHP sort array alphabetically using a subarray value
PhpArraysPhp Problem Overview
> 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 https://stackoverflow.com/questions/2477496/php-sort-array-by-subarray-value but it didn't help much. Any ideas how to do this?
Php Solutions
Solution 1 - Php
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);
Solution 2 - Php
usort
is your friend:
function cmp($a, $b)
{
return strcmp($a["name"], $b["name"]);
}
usort($array, "cmp");