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 生物医学数据分析。基础课程就v经常唱课程舅成牛逼
  • ¥15 云环境云开发云函数对接微信商户中的分账功能
  • ¥15 空间转录组CRAD遇到问题
  • ¥20 materialstudio计算氢键脚本问题
  • ¥15 有没有代做有偿主要做数据可视化部分即可(2023全国高考更省一本线理科类)
  • ¥15 配置FPT报错,该如何处理
  • ¥15 请大家看一下这个代码咋写,一点思路都没有,最好能做一下,不要伪代码,有偿
  • ¥15 有偿请人帮写个安卓系统下禁止装软件及禁止拷入文件的程序
  • ¥100 用 H.265 对音视频硬编码 (CUDA)
  • ¥20 mpich安装完成后出问题