1

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?

1
  • $items = $value1; Commented Sep 14, 2017 at 5:36

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.