I am trying to format an array in php . It does not return in expected json format . Here is details.
$categories = category::where('cat_flag','Y')->pluck('cat_name as category_name')->toArray();
$items = item::leftjoin('categories','items.cat_id' ,'=', 'categories.id')
->where('item_flag','Y')
->get([
'item_name',
'items.cat_id as category_id',
'cat_name as category_name'
])->toArray();
$formatedArray = [];
foreach ($categories as $category) {
foreach ($items as $item) {
if ($item['category_name'] == $category) {
$formatedArray['cat_name'] = $category;
$formatedArray['datas'][] = $item;
}
}
}
my expected output is like bellow. but there is logical error in array format part . I am not getting properly how to format that. Thanks in advance
[
{
"cat_name" : "food",
"datas" : [
{
"item_name": "item2",
"category_id": "1"
},
{
"item_name": "item4",
"category_id": "1"
}
]
},
{
"cat_name" : "drinks",
"datas" : [
{
"item_name": "coca cola",
"category_id": "4"
}
]
}
]
But my output showing like . All items are in same category
{
"cat_name": "cat4",
"datas": [
{
"item_name": "item2",
"category_id": "1"
},
{
"item_name": "item22",
"category_id": "2"
}
]
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire