How to combine array of data and make is more easy to use

Viewed 28

I am working with a filter that I can use after the search so that way I created a table in the database and insert some category and its sub categories and now I want to combine all of the to make a tree like structure. But I am stuck with this

Now How can I achieve this?

[
  {
    "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"
  }
  ]

to this type of result :

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

Without using a long type of for loop because it consume more time.

2 Answers

You can do something like this:

$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));

Try This

$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();
Related