0

I have a 3 dimensional array whose structure looks like the following. Let's call the inner-most arrays as records for clarity. I need to sort the outermost array in such a way that it gets sorted from newest to oldest.

Array (
[0] => Array (
        [0] => Array (
                         [personNum] => 2
                         [type] => comment
                         [datetime] => 2019-05-15 11:29:45
                     ),
        [1] => Array (
                         [personNum] => 3
                         [type] => status
                         [datetime] => 2019-05-26 15:59:53
                     )
       ),

[1] => Array (
        [0] => Array (
                         [personNum] => 3
                         [type] => status
                         [datetime] => 2019-05-26 15:59:53
                     )
        [1] => Array (
                         [personNum] => 4
                         [type] => status
                         [datetime] => 2019-05-26 16:04:24
                     )
      )
)

I have checked this and this links, and I know that custom functions is the way to go, and i am trying to understand it for 2D arrays but i am not getting a hang of how it would work for 3D arrays.

Shy
  • 542
  • 8
  • 20

2 Answers2

1

You can attempt to use usort:
Sort an array by values using a user-defined comparison function https://www.php.net/manual/en/function.usort.php

usort($allArray,function($a,$b){
     return $a[0]['dateTime']-$b[0]['dateTime'];
})
Thrallix
  • 699
  • 5
  • 20
1

You can do this as a two-stage process. First, use array_walk with array_multisort to sort the inner arrays by datetime. Then use usort, comparing the maximum datetime values from the inner arrays:

array_walk($arr, function (&$v) { array_multisort(array_column($v, 'datetime'), SORT_DESC, $v); });
usort($arr, function ($a, $b) {
    return strcmp(max(array_column($b, 'datetime')), max(array_column($a, 'datetime')));
});
print_r($arr);

Output:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [personNum] => 4
                    [type] => status
                    [datetime] => 2019-05-26 16:04:24
                )
            [1] => Array
                (
                    [personNum] => 3
                    [type] => status
                    [datetime] => 2019-05-26 15:59:53
                )
        )
    [1] => Array
        (
            [0] => Array
                (
                    [personNum] => 3
                    [type] => status
                    [datetime] => 2019-05-26 15:59:53
                )
            [1] => Array
                (
                    [personNum] => 2
                    [type] => comment
                    [datetime] => 2019-05-15 11:29:45
                )
        )
)

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95