# Combining arrays

Go to solution Solved by Irate,

## Recommended Posts

I have 2 arrays :

\$array1=

Array (
[0] => Array (
[id] => 411
[pa] => book
[rm] => 32)
[1] => Array (
[id] => 974
[pa] => journal
[rm] => 76)
[2] => Array (
[id] => 3041
[pa] => book
[rm] => 85 )
[3] => Array (
[id] => 3852
[pa] => paper
[rm] => 60 )
)

\$array2=

Array (
[0] => Array (
[AU] => 3041
[NL] => 1490240
[CID] => 52
[1] => Array (
[AU] => 974
[NL] => 1490241
[CID] => 76
[2] => Array (
[AU] => 390
[NL] => 1491023
[CID] => 56 )
)

where the id field in \$array1 should match the AU field in \$array2 (although there won't always be a match in \$array2).

I want to combine the 2 arrays into 1, where all the rows in \$array1 are retained, along with any fields in \$array2 that are not in \$array1. Like this -

Array (
[0] => Array (
[id] => 411
[pa] => book
[rm] => 32)
[NL] =>
[CID] =>  )
[1] => Array (
[id] => 974
[pa] => journal
[rm] => 76)
[NL] => 1490241
[CID] => 76 )
[2] => Array (
[id] => 3041
[pa] => book
[rm] => 85
[NL] => 1490240
[CID] => 52 )
[3] => Array (
[id] => 3852
[pa] => paper
[rm] => 60
[NL] =>
[CID] =>  )
)

I'd appreciate some assistance about how best to do this. I've been using various combinations of in_array so far, with no luck.

##### Share on other sites

Try using "array_merge" and "array_merge_recursive" php functions

##### Share on other sites

Thanks for your help, pbs. I'm not having much luck, though, as these two functions just append one array to the bottom of the other, without doing the combining bit.

##### Share on other sites

• Solution

Try using a for loop.

```<?php

\$array1 = array(...);
\$array2 = array(...);

for(\$i = 0; \$i < 4; \$i++)
{
array_push(\$array1[i], \$array2[i]);
return \$array1;
}

...

?>```
##### Share on other sites

Thanks heaps, Irate. With your array_push suggestion, I was finally able to figure it out.

##### Share on other sites

Mmm, you're welcome.

If you need more help with array_push(), go here: http://php.net/manual/en/function.array-push.php

##### Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.