1

I have a associative array in the following format:

How to sort the array by 'c_name' in ascending order

Array
(
    [country_detials] => Array
        (
            [0] => Array
                (
                    [c_id] => AD
                    [c_name] => Andorra             
                )

            [1] => Array
                (
                    [c_id] => AE
                    [c_name] => United Arab Emirates
                )
   )

)
user2629419
  • 443
  • 1
  • 8
  • 20

2 Answers2

2

use custom comparison function. It's pretty quick and easy to do. Try this:

function sortingFun($item1,$item2)
{
    if ($item1['c_id'] == $item2['c_id']) return 0;
    return ($item1['c_id'] < $item2['c_id']) ? 1 : -1;
}
usort($yourarray,'sortingFun');
print_r($yourarray);
Mahendra Jella
  • 5,450
  • 1
  • 33
  • 38
1

you can use uasort and create a comparing function as you like, I did it for you, you should adjust the comparing function as you like.

$array = array(
    array(
        'c_id' =>'AD',
        'c_name' =>'Andorra',
    ),
    array(
        'c_id' =>'AE',
        'c_name' =>'United Arab Emirates',
    ),
)


// Comparison function
function cmp($a, $b) {
    if ( strcmp ( $a['c_name'],$b['c_name'] ) ) {
        return 1;
    }

}



// Sort and print the resulting array
uasort($array, 'cmp');
Tzook Bar Noy
  • 11,337
  • 14
  • 51
  • 82