【问题标题】:How can I work with nested collection in laravel?如何在 laravel 中使用嵌套集合?
【发布时间】:2016-07-30 05:51:32
【问题描述】:

我在集合中的集合看起来像这样:

=> [
 [
"id" => 3,
   "parent_id" => 2,
    "depth" => 1,
   "children" => [
     [
       "id" => 4,
       "parent_id" => 3,
       "depth" => 2,
       "children" => [
         [
           "id" => 5,
           "parent_id" => 4,
           "depth" => 3,
           "children" => [
             [
  [...]

我该怎么做?

 $result->count();

这个返回1

它的行为就像只有 1 个集合,所以我什至不能使用 map 或 each 来过滤它。我需要过滤最大深度为 4。

我试过reject(),但也没有用。

我可以将它转换为数组,但我想使用不错的收集方法...

【问题讨论】:

    标签: php laravel collections


    【解决方案1】:

    您需要遍历您的集合项目

    $result->children->map(function ($item) {
        // do some stuff with $item or you can no map through its children
        $item->children->map(function ($nestedItem) {
            // do some stuff with $nestedItem etc//
        });
    });
    

    另一种方法是使用foreach 声明

    【讨论】:

    • 这返回我:空
    • 在这里发布您的代码,而不仅仅是变量的转储
    • 我在我的用户模型上使用这个github.com/franzose/ClosureTable。为了得到这个转储,我只做: $result = $user->getDescendantsTree();我不能在这里发布所有的闭包表类,但结果是一个嵌套集合。
    【解决方案2】:

    先将集合转成Array再使用

     count($result, COUNT_RECURSIVE)
    

    【讨论】:

      猜你喜欢
      • 2016-07-28
      • 2021-11-04
      • 2020-02-21
      • 2020-11-26
      • 1970-01-01
      • 2021-03-02
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多