Mike
Mike

Reputation: 980

combining arrays but keep keys?

I'm trying to combine two arrays but keep their keys in place.

For instance, I have my $artist_ids array below:

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

And I have my $song_ids array:

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

Now, if I use array_merge($artist_ids, $song_ids), it looks like it creates a new array and tacks on $song_ids to the bottom of my $artist_ids; totally disregarding the keys -- $artist_ids[1] is suddenly [0] with the rest trailing after.

What can I use that keeps the keys in place? I'd like my output to look like:

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

Upvotes: 2

Views: 72

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219930

Just use the overloaded + to merge the arrays:

$new_array = $artist_ids + $song_ids;

See it here in action: http://codepad.viper-7.com/1bJAfH

Upvotes: 3

Related Questions