【问题标题】:How to combine array of data and make is more easy to use如何组合数据数组并使其更易于使用
【发布时间】:2021-04-01 03:51:49
【问题描述】:

我正在使用一个可以在搜索后使用的过滤器,这样我就在数据库中创建了一个表并插入了一些类别及其子类别,现在我想将所有这些组合成一个树状结构。但我坚持这个

现在我怎样才能做到这一点?

[
  {
    "parent_category": "Recruitment",
    "category_name": "Job description"
  },
  {
    "parent_category": "Recruitment",
    "category_name": "Forms"
  },
   {
    "parent_category": "Performance management system",
    "category_name": "Job description"
  },
  {
    "parent_category": "Exit",
    "category_name": "Job description"
  }
  ]

对于这种类型的结果:

[
  {
    "parent_category": "Recruitment",
    "category_name": "Job description, Forms"
  },
   {
    "parent_category": "Performance management system",
    "category_name": "Job description"
  },
  {
    "parent_category": "Exit",
    "category_name": "Job description"
  }
  ]

不使用长类型的 for 循环,因为它消耗更多时间。

【问题讨论】:

  • 第一个结果应该是 category_name: Forms, Forms 你的例子,不是吗?
  • 请仔细检查您的示例
  • 问题已编辑

标签: laravel laravel-8


【解决方案1】:

试试这个

$data = [
    [
        "parent_category" => "Recruitment",
        "category_name" => "Job description",
    ],
    [
        "parent_category" => "Recruitment",
        "category_name" => "Forms",
    ],
    [
        "parent_category" => "Performance management system",
        "category_name" => "Job description",
    ],
    [
        "parent_category" => "Exit",
        "category_name" => "Job description",
    ],
];
$result = collect($data)->groupBy('parent_category')->map(function ($categories, $parentCategory) {
    return [
        'parent_category' => $parentCategory,
        'category_name' => collect($categories)->pluck('category_name')->unique()->join(', '),
    ];
})->values();

【讨论】:

    【解决方案2】:

    你可以这样做:

    $result = [];
    
    foreach ($categories as $category) {
        if (!isset($result[$category->parent_category])) {
            $result[$category->parent_category] = $category;
        } else {
            $result[$category->parent_category]->category_name .= ', ' . $category->category_name;
        }
    }
    
    echo json_encode(array_values($result));
    

    【讨论】:

    • 这其实是我想要的,感谢@HTMHell的帮助
    猜你喜欢
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多