使用简单数组合并1个多维数组

时间:2014-11-20 16:25:28

标签: php arrays multidimensional-array

我正在尝试合并2个数组:1个多维数据库和另一个数组:

多维数组 - $_SESSION["products"]

array (size=2)
  0 => 
    array (size=4)
      'name' => string 'Lg Monitor' (length=10)
      'code' => string '30' (length=2)
      'qty' => string '1' (length=1)
      'price' => string '1300.50' (length=7)
  1 => 
    array (size=4)
      'name' => string 'Smasung Monitor' (length=15)
      'code' => string '29' (length=2)
      'qty' => string '1' (length=1)
      'price' => string '2300.50' (length=7)

简单数组 - $qty

array (size=2)
  0 => string '2' (length=1)
  1 => string '3' (length=1)

预期输出

array (size=2)
  0 => 
    array (size=4)
      'name' => string 'Lg Monitor' (length=10)
      'code' => string '30' (length=2)
      'qty' => string '2' (length=1) // notice the qty change
      'price' => string '1300.50' (length=7)
  1 => 
    array (size=4)
      'name' => string 'Smasung Monitor' (length=15)
      'code' => string '29' (length=2)
      'qty' => string '3' (length=1) // notice the qty change
      'price' => string '2300.50' (length=7)

我试过了:

foreach ($_SESSION["products"] as $cart_itm){
    foreach($qty as $qt) {
        $cart_itm['qty'] = $qt;
    }
 }

但没有奏效,cart_itm['qty']保持不变(1)。

1 个答案:

答案 0 :(得分:1)

试试这个:

foreach ($_SESSION["products"] as $key => &$cart_itm){
    $cart_itm['qty'] = $qty[$key];
}