You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用for循环在Laravel/Livewire中构建指定结构的多维数组?

修正Laravel/Livewire多维数组整理代码

你的代码存在几个关键问题导致输出结构不符合预期:

  • 变量大小写不一致:$I与$i、$dB与$db的拼写错误会直接导致循环逻辑失效
  • 内层循环每次覆盖$vp变量,没有累加当前属性对应的所有「值-价格」键值对
  • 最终赋值方式错误,没有将属性名直接作为properties数组的顶层键

以下是修正后的代码(保留你初始的循环思路):

public $product, $properties;

public function mount($id)
{
    $this->product = Product::with('attr')->findOrFail($id);
    $this->properties = [];
    $attrTotal = count($this->product->attr);

    for ($i = 0; $i < $attrTotal; $i++) {
        $currentAttr = $this->product->attr[$i];
        $attrTitle = $currentAttr->title;
        $attrId = $currentAttr->id;
        
        // 初始化当前属性的「值-价格」数组
        $valuePriceMap = [];
        // 获取当前属性关联的所有值与价格数据
        $attrItems = DB::table('attr_product')
            ->where('product_id', $id)
            ->where('attr_id', $attrId)
            ->get();
        $itemTotal = count($attrItems);

        for ($j = 0; $j < $itemTotal; $j++) {
            $item = $attrItems[$j];
            $valuePriceMap[$item->value] = $item->price;
        }

        // 将属性名作为顶层键,存入最终数组
        $this->properties[$attrTitle] = $valuePriceMap;
    }
}

更简洁的Laravel集合实现方案

如果你的Product与Attr模型已正确定义多对多关联(中间表包含value和price字段),可以直接用Laravel集合方法替代手动循环,代码更简洁高效:

public $product, $properties;

public function mount($id)
{
    $this->product = Product::with('attr')->findOrFail($id);
    
    $this->properties = $this->product->attr
        ->groupBy('title')
        ->map(function ($attrGroup) {
            return $attrGroup->pluck('pivot.price', 'pivot.value')->toArray();
        })
        ->toArray();
}

内容的提问来源于stack exchange,提问作者foad elyasi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 10:35:21