【问题标题】:Is there an alternative for array_merge?array_merge 有替代方案吗?
【发布时间】:2019-07-12 15:59:51
【问题描述】:

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

我尝试过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"
      ]

【问题讨论】:

标签: php arrays laravel-5.4


【解决方案1】:

解决方案是将您的 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 数组的每个元素,每次它用新值替换旧值,因此你得到 last 的值索引,即最终结果中的“6”。

【讨论】:

    【解决方案2】:

    您需要按照与$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++;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-29
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 2018-02-26
      相关资源
      最近更新 更多