1

I have these 2 arrays coming from 2 separate SQL statements.

1st array:

$a1 = array(
    array('referral_count' => 213),
    array('referral_count' => 88),
    array('referral_count' => 35)
);

2nd array:

$a2 = array(
    array('ocean_company_id' => 524, 'customer_company_id' => 522),
    array('ocean_company_id' => 527, 'customer_company_id' => 522),
    array('ocean_company_id' => 544, 'customer_company_id' => 543)
);

Now what I want to do is combine both arrays to become:

$a3 = array(
    array(
        'ocean_company_id' => 524,
        'customer_company_id' => 522,
        'referral_count' => 213),
    array(
        'ocean_company_id' => 527,
        'customer_company_id' => 522,
        'referral_count' => 88),
    array(
        'ocean_company_id' => 544,
        'customer_company_id' => 543,
        'referral_count' => 35)
);

I tried array_merge and array_merge_recursive but it is appending to the array instead of combining it. Thanks!

PS. I have other arrays I want to combine as well, but this is the general idea.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
Knide
  • 111
  • 1
  • 7
  • 1
    Before going the PHP side, could the SQL be combined into one query? – chris85 Feb 23 '16 at 16:56
  • Sadly it can not be combined :( I already tried that route since there are a lot more other data needed from the main SQL statement. – Knide Feb 23 '16 at 16:58
  • I have 1 main SQL statement which extracts the different ids, and inside my while loop I need the ids to query to other tables to get the other data/counts. thus the need to combine the results into 1 array. – Knide Feb 23 '16 at 16:59
  • [`array_merge_recursive()`](http://php.net/manual/en/function.array-merge-recursive.php) doesn't work because your arrays have numeric keys. – axiac Feb 23 '16 at 17:08

2 Answers2

2

You can use a buffer. Suppose your arrays have the same length.

$result = array();

foreach ($array1 as $i => $arr)
{
    $result[$i] = array_merge($arr, $array2[$i]);
}

var_dump($result);
romellem
  • 5,792
  • 1
  • 32
  • 64
Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84
1

There are a lot of ways to do this. Here's a kind of weird way to add the values from the first array to the second array.

for ($i=0; isset($a1[$i]); $a2[$i]['referral_count'] = $a1[$i]['referral_count'], $i++);

This is basically the same thing as

$i = 0;
while (isset($a1[$i])) {
    $a2[$i]['referral_count'] = $a1[$i]['referral_count'];
    $i++;
}

The advantage to this approach is that there are no function calls and no additional variables are created (except $i);

If you don't want to change your input arrays, you can use array_map with array_merge to combine them into a new array:

$a3 = array_map('array_merge', $a2, $a1);

The advantage to this approach is that, because both of these functions take a variable number of arguments, you can combine as many arrays as you like.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80