【问题标题】:Array merging product with same ID数组合并具有相同ID的产品
【发布时间】:2019-11-15 03:31:13
【问题描述】:

我对此进行了编码以获得一个包含订单中所有产品的数组

$sync_data = [];
    for ($i = 0; $i < count($request['product_id']); $i++) {
        $sync_data[$request->input('product_id')[$i]] = [
            'sequence_no' => $i+1,
            'type' => 'order',
            'quantity' => $request->input('quantity')[$i],
            'listprice' => $request->input('listprice')[$i],
            'discount_percent' => NULL,
            'discount_amount' => $request->input('discount_amount')[$i],
            'comment' => $request->input('comment')[$i],
            'description' => '',
            'tax1' => $request->input('tax1')[$i],
            'tax2' => $request->input('tax2')[$i],
            'tax3' => NULL,
            'tax4' => NULL,
            'campaign_id' => $request->input('campaign_id')[$i]
        ];            
    }

但它正在合并具有相同 ID 的产品,所以我得到了这个

array:2 [▼
  194 => array:13 [▶]
  191 => array:13 [▶]
]

我想要这个

array:2 [▼
  194 => array:13 [▶]
  194 => array:13 [▶]
  191 => array:13 [▶]
]

有人可以向我解释我缺少什么吗?

提前致谢 =)

【问题讨论】:

  • 数组中不能有多个具有相同键的值。您希望 $sync_data[194] 在您的示例中为您提供什么?
  • 这能回答你的问题吗? How to allow duplicate keys in php array
  • 如果你想在一个数组中有重复的条目,你不能使用相同的键。您可以有一个索引数组,并将 'product_id' =&gt; $request-&gt;input('product_id')[$i] 设置为您的数组键之一,等等。
  • 我只是在我的订单中总共添加了 3 个产品,其中 2 个产品相同,因此它们具有相同的 ID (194),所以我的代码正在合并 2 个产品,我不知道我应该编码这个。
  • 我应该在哪里插入这个? 'product_id' => $request->input('product_id')[$i]

标签: php arrays laravel


【解决方案1】:

找到了 =) 谢谢大家的帮助

for ($i = 0; $i < count($request['product_id']); $i++) {
            $sync_data[] = [
                'sequence_no' => $i+1,
                'type' => 'order',
                'quantity' => $request->input('quantity')[$i],
                'listprice' => $request->input('listprice')[$i],
                'discount_percent' => NULL,
                'discount_amount' => $request->input('discount_amount')[$i],
                'comment' => $request->input('comment')[$i],
                'description' => '',
                'tax1' => $request->input('tax1')[$i],
                'tax2' => $request->input('tax2')[$i],
                'tax3' => NULL,
                'tax4' => NULL,
                'product_id' => $request->input('product_id')[$i],
                'campaign_id' => $request->input('campaign_id')[$i]
            ];    

        }
        foreach ($sync_data as $product) {            
            $order->products()->attach($product['product_id'], $product);
        }

【讨论】:

    猜你喜欢
    • 2014-10-08
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 2021-02-25
    • 1970-01-01
    • 2011-08-18
    相关资源
    最近更新 更多