vinnylinux
vinnylinux

Reputation: 7024

Sorting multi-dimensional array by key and any children keys?

I'm scratching my head over this one. I a dataset similar to the following:

$data = [
    [
        'name' => 'Brian',
        'account' => [
            [
                'id' => 1,
            ]
        ]
    ],
    [
        'name' => 'Adam',
        'account' => [
            [
                'id' => 3,
            ],
        ]
    ],
    [
        'name' => 'Chris',
        'account' => [
            [
                'id' => 4,
            ],
        ]
    ],
    [
        'name' => 'Adam',
        'account' => [
            [
                'id' => 2,
            ],
        ]
    ],
    [
        'name' => 'David',
        'account' => [
            [
                'id' => 5,
            ],
        ]
    ],
    [
        'name' => 'Esther',
        'account' => [
            [
                'id' => 6,
            ],
        ]
    ],
];

And I am trying to sort it by the name, and optionally, by the account ID. I imagined this would be an easy task for multisort, but I stumbled upon the recursive nature of the task. I have to detect if any of the childrens are arrays as well, and then, get their keys and sort the root element.

The expected outcome:

Adam (id: 2)
Adam (id: 3)
Brian (id: 1)
Chris (id: 4)
David (id: 5)
Esther (id: 6)

Upvotes: 1

Views: 37

Answers (1)

Xupitan
Xupitan

Reputation: 1681

You can use usort() for order by same as :

usort($data, function($a, $b){
    if ($a['name'] > $b['name']) return 1;
    if ($a['name'] < $b['name']) return -1;
    if ($a['account'][0]['id'] > $b['account'][0]['id']) return 1;
    if ($a['account'][0]['id'] < $b['account'][0]['id']) return -1;
});

You can check it in https://onlinephp.io/c/70893

Upvotes: 1

Related Questions