Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sort array alphabetically using a subarray value [duplicate]

Tags:

arrays

php

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?

like image 911
user6 Avatar asked May 07 '12 15:05

user6


2 Answers

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);
like image 191
Marian Zburlea Avatar answered Oct 26 '22 17:10

Marian Zburlea


usort is your friend:

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

usort($array, "cmp");
like image 20
ccKep Avatar answered Oct 26 '22 15:10

ccKep