-1

I want to sort this array in ascending order by 'money'.

Here is my input array.

$array = array(
            array(
               'user' => array(
                   'money' => 4,
                   'fname' => 'abc'
                ),
           ),
            array(
               'user' => array(
                   'money' => 2,
                   'fname' => 'def'
               ),
            ),
            array(
               'user' => array(
                   'money' => 8,
                   'fname' => 'FGH'
                ),
            ),
            array(
                'user' => array(
                    'money' => 5,
                    'fname' => 'xYz'
                ),
            )
        );
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
Rajiv
  • 31
  • 7

1 Answers1

0

Try this:

function cmp_sort($x,$y) {           //Your function to compare two keys
    if ($x===$y)
        return 0;
    else
        return ($x>$y?1:-1);
}

uasort($array,'cmp_sort');    //Call user-defined compare function
echo "<pre>";
print_r($array);    
echo "</pre>";

Hope this helps.

Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
  • It is working. How can I use this ascending or descending by parameter. – Rajiv Mar 31 '16 at 12:34
  • You may change this return ($x>$y?1:-1); to return ($x>$y?-1:1); if it's descending. In that case, we can pass an extra parameter and use another if. – Indrasis Datta Mar 31 '16 at 12:36