Array_merge в laravel - PullRequest
       12

Array_merge в laravel

0 голосов
/ 08 декабря 2018

У меня есть данные, я возвращаю их в коллекцию, но они не возвращаются, как я хочу, и мне нужна помощь, чтобы исправить это.

вывод

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

1 Ответ

0 голосов
/ 08 декабря 2018

Вы можете приобрести все товары этой категории, ее детей и внуков:

$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

...