I want to get unlimited json loop with category parent_id but I couldn’t find how to do that. Do while I searched but. I couldn’t find the source. How can I do the foreach loop do while? Can you guide me on this?
JavaScript
x
--- Table ---
id
parent_id
name
Json result;
JavaScript
[
{
"id": 1,
"text": "Tabletler",
"children": [
{
"id": 2,
"text": "Apple",
"children": [
{
"id": 3,
"text": "Apple iPad"
}
]
}
]
}
]
Laravel code;
JavaScript
public function index()
{
$category = CategoryEntity::with('categoryEntityValue')->get()->toTree();
$categoryArr = [];
foreach ($category as $cat) {
$childrenArr = [];
foreach ($cat->children as $child) {
$categoryThreeArr = [];
foreach ($child->children as $childThree) {
$categoryThreeArr[] = [
'id' => $childThree->id,
'text' => $childThree->categoryEntityValue[0]->name
];
}
$childrenArr[] = [
'id' => $child->id,
'text' => $child->categoryEntityValue[0]->name,
'children' => $categoryThreeArr
];
}
$categoryArr[] = [
'id' => $cat->id,
'text' => $cat->categoryEntityValue[0]->name,
'children' => $childrenArr
];
}
return response()->json($categoryArr, 200);
}
Advertisement
Answer
A recursive map operation seems perfect for this situation.
If you don’t mind having element with empty children in your json ('children': []
), then this should work.
JavaScript
$formatted = $category->map($recursive = function ($item) use (&$recursive) {
return [
'id' => $item->id,
'text' => $item->category_entity_value[0]->name,
'children' => $item->children->map($recursive)
];
});
If you don’t want that, then adding a bit of logic is needed.
JavaScript
$formatted = $category->map($recursive = function ($item) use (&$recursive) {
$map = [
'id' => $item->id,
'text' => $item->category_entity_value[0]->name
];
if ($item->children->isNotEmpty()) {
$map['children'] = $item->children->map($recursive);
}
return $map;
});
Finally simply return the results.
JavaScript
return response()->json($formatted, 200)