php - combine two arrays of arrays by key -
how combine 2 arrays of arrays 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, should match based on provided field instead of natural order.
what tried. doesn't efficient though.
public function combinearraysbykey($array_1, $array_2, $key = 'id') { $combined_array = array(); foreach($array_1 $sub_array_1) { foreach($array_2 $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; }
[my code] doesn't efficient though.
you need loop once on each of 2 arrays.
in example function, code inside nested loops ran count($array_1) * count($array_2)
times. whereas looping 1 time on each array count($array_1) + count($array_2)
times.
(obviously, number same when there 2 items in each array savings add up.)
so, in code, alternative like:
$combined_array = array(); foreach(array($array_1, $array_2) $rows) { foreach($rows $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;
Comments
Post a Comment