繁体   English   中英

是否有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_quantity值相同的顺序处理$medicine_order值,可以通过将键与每个数组匹配来完成。 尝试以下方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM