简体   繁体   English

数组索引操作PHP

[英]Array index manipulation php

I have a question here. 我在这里有一个问题。 Let's say I have an array of the form: 假设我有以下形式的数组:

Array
(
     [0] => Array
         (
             [0] => Array
                 (
                     [A] => Array
                         (
                             [id] => 1
                             [firstname] => John
                             [lastname] => Smith
                             [email] => jsmith@gmail.com
                         )

                     [B] => Array
                         (
                         )

                 )

         )

     [1] => Array
         (
             [0] => Array
                 (
                     [A] => Array
                         (
                             [id] => 2
                             [firstname] => Tommy
                             [lastname] => Tom
                             [email] => ttom@gmail.com
                         )

                     [B] => Array
                         (
                         )

                 )

         )

)

How can I replace the index of the outer array by the index of the inner array in order to have an array like this: 我如何用内部数组的索引替换外部数组的索引,以便拥有这样的数组:

Array
(
        [0] => Array
            (
                [A] => Array
                    (
                        [id] => 1
                        [firstname] => John
                        [lastname] => Smith
                        [email] => jsmith@gmail.com
                    )

                [B] => Array
                    (
                    )

            )



        [1] => Array
            (
                [A] => Array
                    (
                        [id] => 2
                        [firstname] => Tommy
                        [lastname] => Tom
                        [email] => ttom@gmail.com
                    )

                [B] => Array
                    (
                    )

            )



)

Thanks in advance! 提前致谢!

对于您的特定情况,另一种选择可能很简单:

$out = array_map('reset', $in);

You have to loop through the arrays and create a new array based on the inner values. 您必须遍历数组并根据内部值创建一个新数组。

$in_array = <your array>;
$out_array = Array();

foreach($in_array as $k => $v) {
    $out_array[$k] = array_shift($v);
}

Here, $out_array[$k] keeps the original top-level array keys, and array_shift($v) says to dig down one level for the values (taking the value at the first element in the mid-level array using array_shift , and applying it as the value for the new array). 在这里, $out_array[$k]保留了原始的顶级数组键,而array_shift($v)表示要为值挖掘一个级别(使用array_shift在中级数组中的第一个元素处获取值,以及将其用作新数组的值)。

//$array is your array
foreach($array as $key=>$value)
{
   $new_array[] = $array[$key];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM