PHP sort array alphabetically using a subarray value

PhpArrays

Php 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");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser6View Question on Stackoverflow
Solution 1 - PhpMarian ZburleaView Answer on Stackoverflow
Solution 2 - PhpccKepView Answer on Stackoverflow