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?
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);
usort
is your friend:
function cmp($a, $b)
{
return strcmp($a["name"], $b["name"]);
}
usort($array, "cmp");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With