vendredi 26 juin 2020

Array formatting in php (used laravel framework)

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();

   foreach ($categories as $category) {
            foreach ($items as $item) {
                if ($item['category_name'] == $category) {
                    $formatedArray['cat_name'] = $category;
                    $formatedArray[$category][] = $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"
                }
             ]
           }
        ]


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3eGoI3B
via IFTTT

Aucun commentaire:

Enregistrer un commentaire