2017-09-14 46 views
1

我有2多維數組2多維數組:映射通過鍵使用PHP

$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' 
     ), 
    ), 
); 

我試圖兩個陣列映射,並添加一個「類型」元素,其等於「B」在$數組2到陣列1列,成爲一個新的數組:

$arrayRes = array(
    [0]=>array(
     [items]=>array(
      'item_code'=>'12345', 
      'price'=>'145', 
      'type' => 'IMG' 
     ), 
    ), 
    [1]=>array(
     [items]=>array(
      'item_code'=>'54321', 
      'price'=>'260', 
      'type' => 'PNG' 
     ), 
    ), 
); 

這就是我想:

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']; 
         } 
        } 
       } 
     } 
    } 

但它一直換貨政...產生錯誤'非法字符串偏移'項目''。任何人都可以注意到我做錯了什麼?

+0

$項目= $值1; – deg

回答

1

簡單的解決方案:

$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; 
} 
+0

您的代碼有效。多謝兄弟! – Tedxxxx