0

I have read the documentation for array_multisort, but I can't figure how to sort this MD array by the branda value descending. Do I need to use a recursive function?

   array(10) { 
    [0]=> array(4) { ["nationality"]=> string(3) "USA" ["branda"]=> int(37) ["brandb"]=> int(491) ["combined"]=> int(9) } 
    [1]=> array(4) { ["nationality"]=> string(5) "India" ["branda"]=> int(32) ["brandb"]=> int(206) ["combined"]=> int(8) } 
    [2]=> array(4) { ["nationality"]=> string(5) "Egypt" ["branda"]=> int(26) ["brandb"]=> int(117) ["combined"]=> int(9) } 
    [3]=> array(4) { ["nationality"]=> string(9) "Indonesia" ["branda"]=> int(18) ["brandb"]=> int(129) ["combined"]=> int(3) } 
    [4]=> array(4) { ["nationality"]=> string(6) "Russia" ["branda"]=> int(64) ["brandb"]=> int(418) ["combined"]=> int(6) } 
    [5]=> array(4) { ["nationality"]=> string(5) "China" ["branda"]=> int(82) ["brandb"]=> int(710) ["combined"]=> int(21) } 
    [6]=> array(4) { ["nationality"]=> string(6) "Turkey" ["branda"]=> int(166) ["brandb"]=> int(536) ["combined"]=> int(28) } 
    [7]=> array(4) { ["nationality"]=> string(11) "Netherlands" ["branda"]=> int(127) ["brandb"]=> int(1498) ["combined"]=> int(23) } 
    [8]=> array(4) { ["nationality"]=> string(6) "Israel" ["branda"]=> int(87) ["brandb"]=> int(1266) ["combined"]=> int(14) } 
    [9]=> array(4) { ["nationality"]=> string(2) "UK" ["branda"]=> int(182) ["brandb"]=> int(2935) ["combined"]=> int(24) } 
    } 
Adam Copley
  • 1,495
  • 1
  • 13
  • 31

3 Answers3

1

Something like this would work

$sortingArray = array(); 

foreach($yourArray as $arrayArray){ 
    foreach($arrayArray as $key => $value){ 
        if(!isset($sortingArray[$key])){ 
            $sortingArray[$key] = array(); 
        } 
        $sortingArray[$key][] = $value; 
    } 
} 

$orderby = "branda";
array_multisort($sortingArray[$orderby],SORT_DESC,$yourArray); 
var_dump($yourArray);
Tom Udding
  • 2,264
  • 3
  • 20
  • 30
1

Simplified version of @Hiphop03199 code is:

// for acsending sort
uasort($input_array, function ($a, $b) { return $a['branda'] - $b['branda']; });  

// for descending sort
uasort($input_array, function ($a, $b) { return $b['branda'] - $a['branda']; });  
u_mulder
  • 54,101
  • 5
  • 48
  • 64
0

I would do it with uasort() https://secure.php.net/manual/en/function.uasort.php:

uasort($input_array, function ($i, $j) {
    $a = $i['branda'];
    $b = $j['branda'];
    if ($a == $b) return 0;
    elseif ($a > $b) return 1;
    else return -1;
});

Note: This chunk of code will modify "$input_array" when it runs.

Hiphop03199
  • 729
  • 3
  • 16