组合数组但保留键?

时间:2013-01-28 02:33:06

标签: php arrays

我正在尝试组合两个阵列但保持其密钥就位。

例如,我的$ artist_ids数组如下:

Array
(
    [1] => Array
    (
        [artist_id] => 12291
        [artist_name] => Maroon 5
    )
)

我有我的$ song_ids数组:

Array
(
[0] => Array
    (
        [id] => 113064
        [title] => Harder To Breathe
        [artist_id] => 12291
        [artist_name] => Maroon 5
    )

[2] => Array
    (
        [id] => 113065
        [title] => This Love
        [artist_id] => 12291
        [artist_name] => Maroon 5
    )

[3] => Array
    (
        [id] => 113066
        [title] => Shiver
        [artist_id] => 12291
        [artist_name] => Maroon 5
    )
}

现在,如果我使用array_merge($ artist_ids,$ song_ids),它看起来像是创建了一个新数组,并将$ song_ids粘贴到我的$ artist_ids的底部;完全无视键 - $ artist_ids [1]突然[0],其余的跟在后面。

我可以使用什么来保持钥匙到位?我希望我的输出看起来像:

Array
(
[0] => Array
    (
        [id] => 113064
        [title] => Harder To Breathe
        [artist_id] => 12291
        [artist_name] => Maroon 5
    )
[1] => Array
    (
        [artist_id] => 12291
        [artist_name] => Maroon 5
    )

[2] => Array
    (
        [id] => 113065
        [title] => This Love
        [artist_id] => 12291
        [artist_name] => Maroon 5
    )

[3] => Array
    (
        [id] => 113066
        [title] => Shiver
        [artist_id] => 12291
        [artist_name] => Maroon 5
    )
}

1 个答案:

答案 0 :(得分:3)

只需使用重载的+来合并数组:

$new_array = $artist_ids + $song_ids;

在此处查看:[{3}}