dtcpvz8162 2019-05-13 17:46
浏览 1110
已采纳

PHP / Laravel:如何在PHP中创建JSON时插入新的json字段?

I am returning JSON to my frontend like this:

    public function newFlavorOrders()
    {
        $orders = request()->user()->ordersPaid;
        return response()->json(['flavor_orders' => $orders]);
    }

and right now, that returns this to the frontend:

{ orders: [
   {
     color: "Green"
     size: "Large",
     order_products: [ {'itemNum': 3, 'imgUrl': "zera.jpg"}, {'itemNum': 5, 'imgUrl': "murto.jpg"} ]
   },
   {
     color: "Blue"
     size: "Large",
     order_products: [ {'itemNum': 3, 'imgUrl': "mcue.jpg"}, {'itemNum': 5, 'imgUrl': "cloa.jpg"} ]
    }
  ]
}

But I want to alter the controller PHP function to add a field to each order_products item. I have the imgURL, but I want to add a processedImgUrl and stub it with true right now. How can I add the field to the above php function when returning the JSON?

  • 写回答

2条回答 默认 最新

  • dpdbu24262 2019-05-13 18:12
    关注

    Without the dataset this may not be exactly accurate but the way to do this is either to perform an array push or do a foreach loop and add create the index to be appended.

    For example:

    public function newFlavorOrders()
    {   
        // CREATE A NEW ARRAY TO ADD THE MODIFIED DATA TO
        $modified = array();
        $orders = request()->user()->ordersPaid;
    
        // LOOP THROUGH AND ADD THE VALUE TO THE ITERATION
        foreach($orders as $row) {
            foreach($row['order_products'] as $val){
                $modified = $val;
                if(!empty($val['imgUrl'])){
                    $modified['processedImgUrl'] = TRUE;
                } else {
                    $modified['processedImgUrl'] = FALSE;
                }
            }
        }
    
        return response()->json(['flavor_orders' => $modified]);
    }
    

    Something like this should work. You need to loop through the first array, then get down to the next level array (order_products).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题