-1

Hey guys I hope a very quick one!

I have an array

array(
(int) 30 => array(
    'score' => (int) 30,
    'max_score' => (int) 40,
    'username' => 'joeappleton',
    'user_id' => '1'
),
(int) 34 => array(
    'score' => (int) 34,
    'max_score' => (int) 40,
    'username' => 'joeappleton',
    'user_id' => '1'
),
(int) 36 => array(
    'score' => (int) 36,
    'max_score' => (int) 40,
    'username' => 'joeappleton',
    'user_id' => '1'
)

)

I need it to be sorted into descending order, by reference of the array key:

array( 
    36 => array('score' => 36, 'max_score' => 40, 'username' => 'joeappleton', 'user_id' => '1'),
    34 => array('score' => 34, 'max_score' => 40, 'username' => 'joeappleton', 'user_id' => '1'),
    30 => array('score' => 36, 'max_score' => 40, 'username' => 'joeappleton', 'user_id' => '1')
);

I've tried krsort() but no joy, it seems to return a bool. Any ideas?

Adrian Forsius
  • 1,437
  • 2
  • 19
  • 29

2 Answers2

0

Ok the issue was that krsort(), uses pass by reference. It sorts the original array and returns a bool.

I changed

return krsort($returnArray); //this returned true

to

krsort($returnArray); return $returnArray;

0

we can use array_multisort,which give the same result you want!!!

<?php 
$people = array( 
(int) 30 => array(
'score' => (int) 30,
'max_score' => (int) 40,
'username' => 'joeappleton',
'user_id' => '1'
),
(int) 34 => array(
'score' => (int) 34,
'max_score' => (int) 40,
'username' => 'joeappleton',
'user_id' => '1'
),
(int) 36 => array(
'score' => (int) 36,
'max_score' => (int) 40,
'username' => 'joeappleton',
'user_id' => '1'
)); 
//var_dump($people); 

$sortArray = array(); 

foreach($people as $person){ 
foreach($person as $key=>$value){ 
    if(!isset($sortArray[$key])){ 
        $sortArray[$key] = array(); 
    } 
    $sortArray[$key][] = $value; 
} 
} 

$orderby = "score"; //change this to whatever key you want from the array 

array_multisort($sortArray[$orderby],SORT_DESC,$people); 

//var_dump($people); 
print_r($people);
?> 
Priyank
  • 3,778
  • 3
  • 29
  • 48