如何组合两个多个数组?

时间:2015-08-17 08:14:40

标签: php arrays

我正在研究动态表单部分,并且添加了重复的字段,为了序列化这个,我想要一个包含两个或更多数组的组合数组,现在用两个数组进行测试,我将这两个结合起来,

$array1 =   Array
(
    [0] => Collect Invoices
    [1439797510547] => Array
    (
        [0] => Bank Name
        [1] => Invoices
    )

    [1] => Comment
);
$array2 =   Array
(
    [0] => repeatField
    [1439797510547] => Array
    (
        [0] => selectBanks
        [1] => text
    )

    [1] => textarea
);
$mixedArray =   array_combine($array1,$array2);

/* Result is like this */
Array
(
    [Collect Invoices] => repeatField
    [Array] => Array
    (
        [0] => selectBanks
        [1] => text
    )

    [Comment] => textarea
)

但我想要一个像这样的答案

Array
(
   [Collect Invices] => repeatField
   [1439797510547] => Array
   (
       [Bank Name] => selectBanks
       [Invoices] => text
   )

   [Comment] => textarea
)

任何人都可以帮助我,请...提前谢谢

1 个答案:

答案 0 :(得分:1)

你在这里交配:

$array1 = array(
            0 => 'Collect Invoices',
            1439797510547 => array(
                0 => 'Bank Name',
                1 => 'Invoices'
            ),
            1 => 'Comment'
        );
        $array2 = array
            (
            0 => 'repeatField',
            1439797510547 => array
                (
                0 => 'selectBanks',
                1 => 'text'
            ),
            1 => 'textarea'
        );


        $result_array = array();

        foreach ($array1 as $key => $value) {
            if (!is_array($value)) {
                $result_array[$value] = $array2[$key];
            }

            if (is_array($value)) {
                foreach ($value as $inner_key => $inner_value) {
                    $result_array[$key][$inner_value] = $array2[$key][$inner_key];
                }
            }
        }

        echo "<pre>";
        print_r($result_array);
        echo "</pre>";

结果是:

Array
(
    [Collect Invoices] => repeatField
    [983466387] => Array
        (
            [Bank Name] => selectBanks
            [Invoices] => text
        )

    [Comment] => textarea
)