我怎样才能通过重新定义键顺序数组

我怎样才能通过重新定义键顺序数组

本文介绍了我怎样才能通过重新定义键顺序数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组,在这里我想用定义数组每个子阵列的键的顺序。让我做出了榜样。

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.

输入数组:

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

这将是巨大的,如果答案是在不到code或最佳优化的答案!

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

推荐答案

这应该为你工作:

只需使用为每个子阵列重新排列元素。使用 $头作为第一个参数,的它,这样的价值观是关键,它定义了键的顺序。

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.

和每一个键,然后在阵列( $头)发现,将填充它的值(每个子阵列, $ v )。

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

作为例子:

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

?>

这篇关于我怎样才能通过重新定义键顺序数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 19:47