skip to Main Content

When you have a nested array like the one below called "grouparray," how do you sort by the "groupvalue" key (DESC, so Group B comes first, Group C second and Group A third)?

I tried ksort($grouparray) but it only sorts by the groupids, so not sure how to specify sorting by "groupvalue"

Array
(
    [15] => Array
        (
            [groupid] => 15
            [groupname] => Group A
            [members] => 2051,1556,1918,1518,1185,1673,1847,1643,2004,1340,1617,1491
            [groupvalue] => 391
        )

    [6] => Array
        (
            [groupid] => 6
            [groupname] => Group B
            [members] => 1825,1037,2077,2084,1482,1880,1690,1202,1227,1840,639,1055
            [groupvalue] => 472
        )

    [11] => Array
        (
            [groupid] => 11
            [groupname] => Group C
            [members] => 351,1239,1407,1852,1244,1353,1167,1307,1278,2052,1056,1351,711,1849,1348,1511
            [groupvalue] => 411
        )
)

2

Answers


  1. You can use usort

    usort($sort, "comFun");
    function comFun($firstVal, $secondVal) {
     return strcmp($firstVal["groupname"], $secondVal["groupname"]);
    }
    
    Login or Signup to reply.
  2. This will sort groupvalue in DESC order

    usort($sort, "comFun");
    function comFun($firstVal, $secondVal) {
     return $firstVal["groupvalue"] < $secondVal["groupvalue"] ? 1 : -1;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search