Reputation: 265
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"
}
]
}
Upvotes: 0
Views: 159
Reputation: 542
Hey dude try this you are comparing string to object
foreach ($categories as $category) {
foreach ($items as $item) {
if ($item['category_name'] == $category) {
if(!empty($formatedArray)){
foreach(formatedArray as $array){
if(!empty($array) && $array['cat_name'] == $category){
array_push($formatedArray['datas'], $item)
}else{
$newArray = [];
$newArray['cat_name'] = $category;
$newArray['datas'][] = $item;
array_push($formatedArray, $newArray);
}
}
}else{
$formatedArray['cat_name'] = $category;
$formatedArray['datas'][] = $item
}
}
}
}
Upvotes: 1
Reputation: 409
I think the following code is the problem: In each iteration, $formattedArray contents are being replaced with new values!
$formatedArray = [];
foreach ($categories as $category) {
foreach ($items as $item) {
if ($item['category_name'] == $category) {
$formatedArray['cat_name'] = $category;
$formatedArray['datas'][] = $item;
}
}
}
Replace the above with this:
$formatedArray = $thisArray = [];
foreach ($categories as $category) {
foreach ($items as $item) {
if ($item['category_name'] == $category) {
$thisArray['cat_name'] = $category;
$thisArray['datas'][] = $item;
$formatedArray[] = $thisArray;
$thisArray = [];
}
}
}
Upvotes: 1