Raja
Raja

Reputation: 3627

How can I rearrange an array by defining the key order?

I have a multidimensional array, where I want to define the order of the keys of each subArray with an array. Let me make an example.

Input array:

$array = array(
           array( "version" => 1, "IP" => 1111, "name" => "bbb"),
           array( "version" => 3, "IP" => 1112, "name" => "aaa"),
           array( "version" => 2, "IP" => 1113, "name" => "ccc")
         );

I want to do something like this:

$a_array = sort_headers($array, array("name", "version", "IP"));

And my expected output would be (Look how the order of the keys changed according to the passed array from above):

$a_array = array(
               array("name" => "bbb", "version" => 1, "IP" => 1111),
               array("name" => "aaa", "version" => 3, "IP" => 1112),
               array("name" => "ccc", "version" => 2, "IP" => 1113)
             );

It would be great if the answer will be in less code or best optimized answer!

Upvotes: 1

Views: 2101

Answers (1)

Rizier123
Rizier123

Reputation: 59681

This should work for you:

Just use array_replace() for each subArray to rearrange your elements. Use $header as first argument and array_flip() it, so that the values are the keys, which define the order of the keys.

And each key, which is then found in the array ($header), will be filled with the value of it (Each subArray, $v).

As example:

Header / Key order:
       Array ( [name] =>   [version] =>   [IP] =>   ) 
                         ↑              ↑         ↑
                         └──┐           │       ┌─┘
                         ┌──┼───────────┘       │
                         │  └───────────────────┼──┐
                         │          ┌───────────┘  │
                         |          │              |
    Array ( [version] => 1 [IP] => 1111 [name] => bbb ) 
(Each) Array:

---------------------
Result:
       Array ( [name] => bbb [version] => 1 [IP] => 1111 ) 

Code:

<?php

    $header = array("name", "version", "IP");

    $array = array_map(function($v)use($header){
        return array_replace(array_flip($header), $v);
    }, $array);

?>

Upvotes: 2

Related Questions