Php: Sort Array Alphabetically Using a String/value in Subarray

by admin Date: 23-08-2013 php arrays sort


If we have an array and inside each value of this array we have another array with age and name for example, and we want to sort the first array by the name of each value in the child arrays we do is using usort  and strcmp functions from php.

Here is an example:

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

This will output:

    Array
(
    [0] => Array
        (
            [name] => Bill
            [age] => 15
        )

    [1] => Array
        (
            [name] => Nina
            [age] => 21
        )

    [2] => Array
        (
            [name] => Peter
            [age] => 17
        )

)
 
by admin Date: 23-08-2013 php arrays sort hits : 20043  
 
 
 
 

Related Posts