array_merge有替代品吗?

Is there an alternative for array_merge?

问题是,我没有得到数组代码的预期结果。

我试过 array_merge,但它所做的只是合并所有数组。

$medicine_order = $request['medicine_id'];

        array:3 [▼
          0 => "25"
          1 => "32"
          2 => "30"
      ]

      $medicine_quantity = $request['medicine_quantity'];

      array:3 [▼
          0 => "3"
          1 => "10"
          2 => "6"
      ]

      $count = 0;
      foreach ($medicine_order as $id) {
        $item = new Historyitem;
        $item->medicine_id = $id;

        foreach ($medicine_quantity as $id2) {
            $item->historyitem_quantity = $id2;
        }
        $item->save();
        $count++;
    }

我想将这些值存储在我的数据库中。

array:3 [▼
          0 => "25"
          1 => "3"
      ]
 array:3 [▼
          0 => "32"
          1 => "10"
      ] 
array:3 [▼
          0 => "30"
          1 => "6"
      ]

但我得到了这些值:

array:3 [▼
          0 => "25"
          1 => "6"
      ]
 array:3 [▼
          0 => "32"
          1 => "6"
      ] 
array:3 [▼
          0 => "30"
          1 => "6"
      ]

解决方案是将 foreach 循环更改为:

$count = 0;
foreach ($medicine_order as $key=>$id) {
    $item = new Historyitem;
    $item->medicine_id = $id;
    $item->historyitem_quantity = $medicine_quantity[$key];
    $item->save();
    $count++;
}

你得到错误结果的原因是,你的内部 foreach 循环,它遍历你的 $medicine_quantity 数组的每个元素,每次它用新值替换旧值,因此你正在获取最后一个索引的值,即最终结果中的“6”。

您需要按照与 $medicine_order 值相同的顺序处理 $medicine_quantity 值,这可以通过将键与每个数组匹配来实现。试试这个:

foreach ($medicine_order as $key => $id) {
    $item = new Historyitem;
    $item->medicine_id = $id;
    $item->historyitem_quantity = $medicine_quantity[$key];
    $item->save();
    $count++;
}