phparrayssortingmultidimensional-arraycustom-sort

Apply custom order of columns in each row of a 2d array


I have a 2d array and I need to reorder the elements of all rows by another flat array:

here is my array:

Array
(
    [0] => Array
        (
            [name] => Haroldas
            [number] => 444
            [address] => g.
            [city] => eee
            [country] => f
            [lastname] => r
        )

    [1] => Array
        (
            [name] => Lukas
            [number] => 999
            [address] => rrr
            [city] => tttt
            [country] => 3
            [lastname] => r
        )
)

This is another array with columns number which show me how to order number (columns order can to be another):

Array
(
    [lastname] => 4
    [name] => 1
    [number] => 5
    [address] => 3
    [city] => 0
    [country] => 2
) 

I need result like this:

Array
    (
        [0] => Array
            (
                [city] => eee
                [name] => Haroldas
                [country] => f
                [address] => g.
                [lastname] => r
                [number] => 444
            )
    ...
    )

Solution

  • This should do the job:

    <?php
    
    $order = [
        'city'     => 0,
        'name'     => 1,
        'country'  => 2,
        'address'  => 3,
        'lastname' => 4,
        'number'   => 5,
    ];
    
    $data = [
        [
            'name'     => 'Haroldas',
            'number'   => '444',
            'address'  => 'g.',
            'city'     => 'eee',
            'country'  => 'f',
            'lastname' => 'r',
        ],
        [
            'name'     => 'Lukas',
            'number'   => '999',
            'address'  => 'rrr',
            'city'     => 'ttt',
            'country'  => 3,
            'lastname' => 'r',
        ],
    ];
    
    foreach ($data as &$entry) {
        uksort($entry, function ($a, $b) use ($order) {
            return strcmp($order[$a], $order[$b]);
        });
    }
    
    print_r($data);
    

    The output is:

    Array
    (
        [0] => Array
            (
                [city] => eee
                [name] => Haroldas
                [country] => f
                [address] => g.
                [lastname] => r
                [number] => 444
            )
    
        [1] => Array
            (
                [city] => ttt
                [name] => Lukas
                [country] => 3
                [address] => rrr
                [lastname] => r
                [number] => 999
            )
    
    )