Monday, 27 August 2018

Sort multidimensional array keys according to a command order of other arrays

Late in the evening and been looking at this one too long guys.
This is the array where the keys are in the correct order.
Array
(
    [FirstName] => 'Timmy'
    [LastName] => 'O Toole'
    [Address] => 'Nowhere'
    [Tel] => '12345'
    [Email] => 'nonone@nowhere.com'
)

I want each record in the following array to match the key ordering as above.
(
    [0] => Array
        (
            [FirstName] => 'Robin'
            [Address] => 'Cave'
            [LastName] => 'Mactimmy'
            [Tel] => '9076'
            [Email] => 'i@o.com'
        )

    [1] => Array
        (
            [Address] => 'uytr'
            [FirstName] => 'Bill'
            [Email] => 'j@k.com'
            [LastName] => 'Gates'
            [Tel] => '7654'
        )

    [2] => Array
        (
            [LastName] => 'Mahoney'
            [Email] => 'y@i.ie'
            [FirstName] => 'Tom'
            [Tel] => '5689'
            [Address] => 'kklll'
        )
)

I have tried ksort and usort also but the array ordering does not seem to be updating.

Basic on your data:
$array = [
    0 => Array
        (
            'FirstName' => 'Robin',
            'Address' => 'Cave',
            'LastName' => 'Mactimmy',
            'Tel' => '9076',
            'Email' => 'i@o.com',
        ),

    1 => Array
        (
            'Address' => 'uytr',
            'FirstName' => 'Bill',
            'Email' => 'j@k.com',
            'LastName' => 'Gates',
            'Tel' => '7654',
        ),

    2 => Array
        (
            'LastName' => 'Mahoney',
            'Email' => 'y@i.ie',
            'FirstName' => 'Tom',
            'Tel' => '5689',
            'Address' => 'kklll',
        )
];

I think it is good solution:
<?php

$order = [ 'FirstName', 'LastName', 'Address', 'Tel', 'Email'];

$result = [];
foreach ($array as $sortable) {
    $result[] = array_merge(array_flip($order), $sortable);
}

print_r($result);

0 comments:

Post a Comment