【问题标题】:Array_merge in laravellaravel 中的数组合并
【发布时间】:2018-12-08 06:32:05
【问题描述】:

我有数据我将它们返回到集合中,但它没有按我的意愿返回,我需要帮助来修复它。

输出

array:11 [▼
  0 => Collection {#2762 ▼
    #items: array:3 [▼
      0 => Product {#2758 ▶}
      1 => Product {#2759 ▶}
      2 => Product {#2760 ▶}
    ]
  }
  1 => Collection {#2792 ▼
    #items: []
  }
  2 => Collection {#2948 ▼
    #items: []
  }
  3 => Collection {#3102 ▼
    #items: []
  }
  4 => Collection {#3216 ▼
    #items: []
  }
  5 => Collection {#2886 ▼
    #items: array:10 [▶]
  }
  6 => Collection {#2920 ▼
    #items: array:3 [▶]
  }
  7 => Collection {#3046 ▼
    #items: array:12 [▶]
  }
  8 => Collection {#3074 ▼
    #items: []
  }
  9 => Collection {#3188 ▼
    #items: array:7 [▶]
  }
  10 => Collection {#3288 ▼
    #items: []
  }
]

代码

$category = Category::where('slug','=',$catslug)->with('childs', 'parent')->first();


$pp1[] = Product::where('category_id',$category->id)->get();

foreach($category->childs as $first){
$pp2[] = Product::where('category_id',$first->id)->get();
if(count($first->childs)> 0){
    foreach($first->childs as $second){
    $pp3[] = Product::where('category_id',$second->id)->get();
    }
}
}

$products = array_merge($pp1,$pp2,$pp3);

dd($products);

它应该返回什么

它应该只返回 1 个数组中的所有数组中的所有产品,而不是按 Collection {#2792 ▼ 分类我只需要获取包含项目的集合,而不是那些为空的集合。

有什么想法吗?

更新

我也试过这个:

$pp1 = [];
      $pp2 = [];
      $pp3 = [];
      $pp1 = Product::where('category_id',$category->id)->get();

      foreach($category->childs as $first){
        $pp2 = Product::where('category_id',$first->id)->get();
        if(count($first->childs)> 0){
          foreach($first->childs as $second){
            $pp3 = Product::where('category_id',$second->id)->get();
          }
        }
      }

它返回:

array_merge(): Argument #1 is not an array

【问题讨论】:

    标签: php laravel array-merge


    【解决方案1】:

    您可以获得该类别的所有产品,它的子级和孙级,

    $category = Category::where('slug','=',$catslug)
                        ->with([
                            'products', 
                            'childs.products', 
                            'childs.childs.products', 
                            'parent'
                         ])
                        ->first()
                        ->toArray();
    
    $products = array_merge([
        data_get($category, 'products'),
        array_collapse(data_get($category, 'childs.*.products')),
        array_collapse(data_get($category, 'childs.*.childs.*.products'))
    ]);
    

    小提琴:https://implode.io/ebXrD8

    【讨论】:

    • 嗨,我没有检查你的代码,但我不知道谁投了反对票,我要检查
    • 您的代码有问题这是返回数据的屏幕截图ibb.co/v1XyqjZ
    • 你检查过我的小提琴吗?是否有相同的数据结构?
    猜你喜欢
    • 2020-04-09
    • 2017-03-07
    • 2016-02-28
    • 2020-08-02
    • 1970-01-01
    • 2019-02-28
    • 2021-03-30
    • 2019-04-10
    • 2018-09-22
    相关资源
    最近更新 更多