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?

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.