waspinator waspinator -4 years ago 71
PHP Question

combine two arrays of arrays by key

How would I combine two arrays of arrays by a key?

For example:

Array 1:

array (
array (
'id' => '1',
'A' => 'ABC'
),
array (
'id' => '2',
'A' => 'DEF'
)
)


Array 2:

array (
array (
'id' => '2',
'B' => '456'
)
array (
'id' => '1',
'B' => '123'
),
)


Combined array:

array (
array (
'id' => '1',
'A' => 'ABC',
'B' => '123'

),
array (
'id' => '2',
'A' => 'DEF',
'B' => '456'
)
)


The combined array order isn't important, but it should match based on a provided field instead of natural order.

what I tried. doesn't look efficient though.

public function combineArraysByKey($array_1, $array_2, $key = 'id')
{
$combined_array = array();

foreach($array_1 as $sub_array_1) {
foreach($array_2 as $sub_array_2) {
if ($sub_array_1[$key] == $sub_array_2[$key]) {
$merged_sub_array = array_merge($sub_array_1, $sub_array_2);
array_push($combined_array, $merged_sub_array);
}
}
}
return $combined_array;
}

Answer Source

[My code] doesn't look efficient though.

You only really need to loop once over each of the two arrays.

In your example function, the code inside the nested loops will be ran count($array_1) * count($array_2) times. Whereas looping one time over each array would only be count($array_1) + count($array_2) times.

(Obviously, the number is the same when there are only 2 items in each array but the savings soon add up.)

So, in code, the alternative could be like:

$combined_array = array();
foreach(array($array_1, $array_2) as $rows) {
    foreach($rows as $row) {
        $current_key = $row[$key];
        if (array_key_exists($current_key, $combined_array)) {
            $combined_array[$current_key] += $row;
        } else {
            $combined_array[$current_key] = $row;
        }
    }
}
return $combined_array;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download