Reputation: 258
I have 2 multi-dimensional arrays:
$array1 = array(
[0]=>array(
[items]=>array(
'item_code'=>'12345',
'price'=>'145'
)
),
[1]=>array(
[items]=>array(
'item_code'=>'54321',
'price'=>'260'
)
),
);
$array2 = array(
[0]=>array(
[A]=>'12345'
[B]=>'IMG'
),
),
[1]=>array(
[A]=>'54321'
[B]=>'PNG'
),
),
);
I am trying to map the two arrays and add a 'type' element, which equals to 'B' column in $array2 into array1, to become a new array:
$arrayRes = array(
[0]=>array(
[items]=>array(
'item_code'=>'12345',
'price'=>'145',
'type' => 'IMG'
),
),
[1]=>array(
[items]=>array(
'item_code'=>'54321',
'price'=>'260',
'type' => 'PNG'
),
),
);
This is where I am trying:
foreach ($array1 as $arr) {
foreach ($arr as $key1 => $value1) {
$items = $value1['items'];
foreach ($items as $item=>$itemValue){
foreach ($array2 as $key2 => $value2){
if($itemValue['item_code'] == $value2['A']){
$items['type'] = $value2['B'];
}
}
}
}
}
But it keeps returning an error 'Illegal string offset 'items''. Could anyone notice what I did wrong?
Upvotes: 1
Views: 241
Reputation: 1633
Simple solution :
$array1 = array(
array(
'items' => array(
'item_code'=>'12345',
'price'=>'145'
),
),
array(
'items'=>array(
'item_code'=>'54321',
'price'=>'260'
),
),
);
$array2 = array(
array(
'A'=>'12345',
'B'=>'IMG'
),
array(
'A'=>'54321',
'B'=>'PNG'
),
);
foreach ($array1 as &$row1) {
$item = $row1['items'];
foreach ($array2 as $row2) {
if ($row2['A'] == $item['item_code']) {
$item['type'] = $row2['B'];
break;
}
}
$row1['items'] = $item;
}
Upvotes: 1