Search code examples
phparrayssortingmultidimensional-arraycustom-sort

Change the position of row elements in a 2d array based on another flat array of key names


I have one array (left) that contains a list of elements, the goal is to sort another arrays (right) keys with the values from the left array.

The left array

Array
(
    [0] => ID
    [1] => FirstName
    [2] => LastName
    [3] => Address
)

The right array

Array
(
    [0] => Array
    (
        [FirstName] => Pim
        [Address] => Finland
        [LastName] => Svensson
        [ID] => 3
    )
    [1] => Array
    (
        [FirstName] => Emil
        [Address] => Sweden
        [LastName] => Malm
        [ID] => 5
    )
)

What I'm trying to accomplish would be similar to this

Array
(
    [0] => Array
    (
        [ID] => 3
        [FirstName] => Pim
        [LastName] => Svensson
        [Address] => Finland
    )

I'm running PHP5.3.


Solution

  • $output = array();
    foreach ( $right as $array ) {
        foreach ( $left as $field ) {
            $temp[$field] = $array[$field];
        }
        $output[] = $temp;
    }