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条)

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建