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

后端 未结 1 1568
栀梦
栀梦 2021-01-23 09:01

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 = arr         


        
1条回答
  •  难免孤独
    2021-01-23 09:13

    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:

    
    

    0 讨论(0)
提交回复
热议问题