我想獲得具有類別 parent_id 的無限 json 回圈,但我找不到如何做到這一點。當我搜索但時做。我找不到源頭。我怎樣才能做foreach回圈做while?你能指導我嗎?
--- Table ---
id
parent_id
name
json結果;
[
{
"id": 1,
"text": "Tabletler",
"children": [
{
"id": 2,
"text": "Apple",
"children": [
{
"id": 3,
"text": "Apple iPad"
}
]
}
]
}
]
Laravel 代碼;
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);
}
uj5u.com熱心網友回復:
遞回映射操作似乎非常適合這種情況。
如果您不介意在您的 json ( 'children': []) 中有帶有空子元素的元素,那么這應該可以作業。
$formatted = $category->map($recursive = function ($item) use (&$recursive) {
return [
'id' => $item->id,
'text' => $item->category_entity_value[0]->name,
'children' => $item->children->map($recursive)
];
});
如果您不希望這樣,則需要添加一些邏輯。
$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;
});
最后簡單地回傳結果。
return response()->json($formatted, 200)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/422878.html
標籤:
