1

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!

5
  • And the function, and the problem? Commented Sep 25, 2015 at 10:03
  • The function is actually just for an example and problem is actually i need the mentioned output in more optimized way. Anyway i can achieve the output using some foreach loops, but if you provide me easiest way to achieve the given output would be great one! Commented Sep 25, 2015 at 10:06
  • 2
    Have you looked into usort()? Commented Sep 25, 2015 at 10:06
  • Need to sort based on Version? Commented Sep 25, 2015 at 10:11
  • 1
    Thanks for the edits @Rizier123, I can realize now how a question would be :) Commented Sep 25, 2015 at 10:40

1 Answer 1

2

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);

?>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.