'php usort deep-nested subarray optimization

Ok Gurus, In searching the web I have seen usort doing similar to my issue but nothing I found really answered this question so I am posting for advice. I have the following array:

$details = array( 
[1]=>array ( 
["2022-02-12"]=>array( 
[0]=>array( ["IN_PUNCH"]=> int(1644927415), ["OUT_PUNCH"]=> bool(false), ["PUNCH_TYP"]=> "CI" ),
[1]=>array( ["IN_PUNCH"]=> int(1644927450), ["OUT_PUNCH"]=> int(1644927471), ["PUNCH_TYP"]=>  "SJ_EJ" ),
[2]=>array( ["IN_PUNCH"]=> int(1644927946), ["OUT_PUNCH"]=> int(1644939760), ["PUNCH_TYP"]=> "SB_EB" ),
[3]=>array( ["IN_PUNCH"]=> int(1644939774), ["OUT_PUNCH"]=> int(1644942307), ["PUNCH_TYP"]=> "SJ_EJ" ),
[4]=>array( ["IN_PUNCH"]=> int(1644942317), ["OUT_PUNCH"]=> bool(false), ["PUNCH_TYP"]=> "SB" )), 
["2022-02-13"]=>array( ),
 ["2022-02-14"]=>array ( 
[0]=>array( ["IN_PUNCH"]=> int(1644947652), ["OUT_PUNCH"]=> bool(false), ["PUNCH_TYP"]=> "CI" ),
[1]=>array( ["IN_PUNCH"]=> int(1644957123), ["OUT_PUNCH"]=> bool(false), ["PUNCH_TYP"]=> "SJ" )
 ), 
["2022-02-15"]=>array( ), 
["2022-02-16"]=>array( ),
 ), 
[2]=>array( 
["2022-02-14"]=>array(
[0]=>array( ["IN_PUNCH"]=> int(1644947652), ["OUT_PUNCH"]=> bool(false), ["PUNCH_TYP"]=> "CI" ),
[1]=>array( ["IN_PUNCH"]=> int(1644957123), ["OUT_PUNCH"]=> bool(false), ["PUNCH_TYP"]=> "SJ" ) 
) ,
["2022-02-15"]=>array( ),
["2022-02-16"]=>array( ),
["2022-02-17"]=>array( )
 )
 )

And I have a need to sort each date sub-array by the "IN_PUNCH" field. To do so I have this:

function sortByOrder($a, $b) {
    if ($a['IN_PUNCH'] < $b['IN_PUNCH']) return -1;    // return -1 if $a is earlier
    return  $a['IN_PUNCH'] > $b['IN_PUNCH'];    // return 1 if $a is later, or 0 if equal
}

foreach($details as $a=> $b){
        
        foreach($b as $c => $d){
              usort($d, 'sortByOrder');
              $details[$a][$c] = $d;
                
    }
}

Which is doing the job, but is there a more optimized way to do this without the nested loops?

php


Solution 1:[1]

Though there is nothing wrong with your approach. But you can also use array_map() to achieve the same thing. Try this

$details = array_map(function($array){ // ~ outer foreach
    return array_map(function($arr){ // ~ inner foreach
        usort($arr, function($a, $b){ // ~ sortByOrder function
            $a = $a['IN_PUNCH'];
            $b = $b['IN_PUNCH'];
            return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);
        });

        return $arr;
    }, $array);
}, $details);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ruleboy21