将2个数组合并为一个具有相同键的数组

时间:2013-10-16 02:50:22

标签: php codeigniter

我想将文件名合并到同一个key.Below是两个数组,我试图使用array_merge但它没有合并到相同的键

Array
(
    [0] => Array
        (
            [episode_id] => 2
            [episode_number] => 1
            [series] => 2012
        )

    [1] => Array
        (
            [episode_id] => 2
            [episode_number] => 2
            [series] => 2013
        )

)
Array
(
    [0] => Array
        (
            [filename] => Enq9nNGnMFY
        )

    [1] => Array
        (
            [filename] => Enq9nsdfdsNGnMFY
        )

)

预期输出应为

Array
(
    [0] => Array
        (
            [episode_id] => 2
            [episode_number] => 1
            [series] => 2012
            [filename] => Enq9nNGnMFY
        )

    [1] => Array
        (
            [episode_id] => 2
            [episode_number] => 2
            [series] => 2013
            [filename] => Enq9nsdfdsNGnMFY
        )

)

任何人都可以帮忙!!!!!!!!!!

3 个答案:

答案 0 :(得分:1)

foreach ($first_array as $key => $item){
$second_array[$key] = array_merge($second_array[$key],$item);
}

第二个数组将包含您想要的内容。

答案 1 :(得分:0)

试试这个:

foreach($array_1 as $key => $value){
    foreach($array_2[$key] as $key2 => $value2){
        array_push($array_1[$key], $value2);
    }
}

$ array_1应该是你的组合数组,即使你不仅仅是文件名。

答案 2 :(得分:0)

试试这个:

<?php
        $array_1 = Array
            (Array('episode_id' => 2, 'episode_number' => 1, 'series' => 2012),
            Array('episode_id' => 2, 'episode_number' => 2, 'series' => 2013)
        );

        $array_2 = Array(Array('filename' => 'Enq9nNGnMFY'), Array('filename' => 'Enq9nsdfdsNGnMFY'));

        foreach ($array_1 as $key => $value) {
            foreach ($array_2[$key] as $key2 => $value2) {
                $array_1[$key][$key2] = $value2;
            }
        }



        echo '<pre>';
        print_r($array_1);
        ?>

第一个数组是你想要的结果