Search code examples
phpmultidimensional-arraymultiple-columns

Change order of multidimensional array columns


I have a multidimensional array in php and i need to change the column order with the order of a second simple array.

EDIT: Although both arrays are the same in regard of values and keys, im using this for export with phpexcel, and it generates the xls file with the order of the given array. I need to change that order so the xls file looks that way.

The array looks like this:

Array
(
    [0] => Array
        (
            [name] => Name1
            [sn] => Sn1
            [somenumber] => 43234234
        )

    [1] => Array
        (
            [name] => Name2
            [sn] => Sn2
            [somenumber] => 4564564
        )

    [2] => Array
        (
            [name] => Name3
            [sn] => Sn3
            [somenumber] => 6575647456745
        )
)

And the second array is this:

Array
        (
            [0] => sn
            [1] => name
            [2] => somenumber
        )

What i need is the first array to be ordered based on the second so it looks like this:

Array
(
    [0] => Array
        (
            [sn] => Name1
            [name] => Sn1
            [somenumber] => 43234234
        )

    [1] => Array
        (
            [sn] => Name2
            [name] => Sn2
            [somenumber] => 4564564
        )

    [2] => Array
        (
            [sn] => Name3
            [name] => Sn3
            [somenumber] => 6575647456745
        )
)

Solution

  • If all keys always present

    // Make template array with correct order of keys
    $template = array_flip($second);
    
    foreach($array as &$x) {
       // replace values in template
       $x = array_replace($template, $x);
    }
    

    demo