Reputation: 129
I have more than one category and inside these categories there is "pages". I want to change the name of this pages
via foreach, but I couldn't merge it. how can i do it?
public function getCategory($lang): array
{
$data = [];
$categories = Category::where('language', $lang)->with('pages')->get();
foreach ($categories as $key => $category) {
$data[] = [
'title' => $category['title'],
'path' => $category['slug'],
];
foreach ($category['pages'] as $keys => $page) {
$data[] = [
'children' => [
'title' => $page['title'],
'path' => $page['slug']
]
];
}
}
return $data;
}
output
[
{
"title": "corporate",
"path": "corporate"
},
{
"children": {
"title": "corporatealt",
"path": "corporatealt"
}
},
{
"children": {
"title": "corporatealt2",
"path": "corporatealt2"
}
},
{
"title": "blabla",
"path": "blabla"
}
]
Upvotes: 0
Views: 34
Reputation: 8355
Try this:
public function getCategory($lang): array
{
$data = [];
$categories = Category::where('language', $lang)->with('pages')->get();
foreach ($categories as $key => $category) {
$d = [
'title' => $category['title'],
'path' => $category['slug']
];
if (!empty($category['pages'])) {
$d['children'] = array_map(function($page){return [
'title' => $page['title'],
'path' => $page['slug']
];}, array_values($category['pages']));
}
$data[] = $d;
}
return $data;
}
Upvotes: 1