1
$data = [
           [
             'cat'=>'A',
             'catOrder'=>2,
              'data'=>[
                        ['name'=>'user', 'order'=>2],
                        ['name'=>'user', 'order'=>1],
                        ['name'=>'user', 'order'=>3]
                      ]
           ],
           [
             'cat'=>'B',
             'catOrder'=>1,
              'data'=>[
                        ['name'=>'user', 'order'=>2],
                        ['name'=>'user', 'order'=>1]
                      ]
           ]
        ]

what is the best way to sort the above array in php by first "catOrder" and then also by "order" field in data array

I tried using first

foreach($data as &$row){ 
 usort($row['data'], function($a, $b){ return strcmp($a['order'], 
     $b['order']);});
}

and then

uasort($data, function($a, $b){ return strcmp($a['catOrder'], $b['catOrder'])});

It seems to be working but I just wanted to know if there is any better and more efficient way?

Arian
  • 465
  • 1
  • 7
  • 18
  • Possible duplicate of [How to sort an array of associative arrays by value of a given key in PHP?](https://stackoverflow.com/questions/1597736/how-to-sort-an-array-of-associative-arrays-by-value-of-a-given-key-in-php) – miken32 Dec 03 '18 at 23:47
  • 1
    `array_multisort()` would be your best bet. Use `array_column()` to get the sort values. – miken32 Dec 03 '18 at 23:48

1 Answers1

1

ksort will be faster than than usort (I'm fairly certain), so I think you can shave off a few ms by converting

foreach($data as &$row){ 
    usort($row['data'], function($a, $b){ return strcmp($a['order'], 
 $b['order']);});
}
uasort($data, function($a, $b){ return strcmp($a['catOrder'], $b['catOrder'])});

To:

foreach($data as $row){
    foreach($row['data'] as $v){
        $row['data'][$v['order']-1] = $v; //assuming 'order' starts at 1
    }
    ksort($row['data']);
    $data[$row['catOrder']-1] = $row; //assuming 'catOrder' starts at 1
}
ksort($data);

You add a few operations with the assignment, but you make up for it in the sort. I did some very basic benchmarks, and the speed increase appears to be somewhere around 50%. This is at the cost of additional ram, though, since I've removed the & from the arrays, resulting in a copy.

ebcode
  • 124
  • 1
  • 5