I have two arrays like this :
Array1
Array
(
[0] => Array
(
[ID] => 101
[Code] => 1075
[Date] => 2012-03-03 17:13:12.433
)
[1] => Array
(
[ID] => 103
[Code] => 175
[Date] => 2012-09-05 20:30:02.217
)
[2] => Array
(
[ID] => 109
[Code] => 178
[Date] => 2012-07-05 20:30:02.217
)
)
Array2
Array
(
[0] => Array
(
[Amount] => 1234
[ID] => 101
)
[1] => Array
(
[Amount] => 1342
[ID] => 103
)
[2] => Array
(
[Amount] => 0
[ID] => 0
)
)
I use this code to combine them based on the matching values of the ID index.
$combined = array();
foreach ($arr as $arrs) {
$comb = array('ID' => $arrs['ID'], 'Code' => $arrs['Code'],'Date' => $arrs['Date'],'Amount' => '');
foreach ($arr4 as $arr2) {
if ($arr2['ID'] == $arrs['ID']) {
$comb['Amount'] = $arr2['Amount'];
break;
}
else {
$comb['Amount'] = $arr2['Amount'];
}
}
$combined[] = $comb;
}
echo print_r($combined);
And here is the desired output I get from this code :
Array
(
[0] => Array
(
[ID] => 101
[Code] => 1075
[Date] => 2012-03-03 17:13:12.433
[Amount] => 1234
)
[1] => Array
(
[ID] => 103
[Code] => 175
[Date] => 2012-09-05 20:30:02.217
[Amount] => 1342
)
[2] => Array
(
[ID] => 109
[Code] => 178
[Date] => 2012-07-05 20:30:02.217
[Amount] => 0
)
)
I want to optimize the code such that
$comb = array('ID' => $arrs['ID'], 'Code' => $arrs['Code'],'Date' => $arrs['Date'],'Amount' => '');
should be generated dynamically rather than hard coded.
And instead of $comb['Amount'] = $arr2['Amount']; I want code to automatically add all the other feilds to the first array where the ID matches.
How do I achieve this?