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

时间:2019-05-13 17:46:34

标签: php json laravel

我将JSON返回到我的前端,如下所示:

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

现在,它将返回到前端:

{ 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"} ]
    }
  ]
}

但是我想更改控制器PHP函数,以便为每个order_products项目添加一个字段。我有imgURL,但是我想添加一个processedImgUrl并立即与true进行存根。返回JSON时,如何在上述php函数中添加字段?

2 个答案:

答案 0 :(得分:0)

在没有数据集的情况下,这可能并不完全准确,但是执行此操作的方法是执行数组推送或执行foreach循环并添加要添加的索引。

例如:

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]);
}

类似的事情应该起作用。您需要遍历第一个数组,然后进入下一个级别的数组(order_products)。

答案 1 :(得分:0)

public function newFlavorOrders()
    {
        $orders = request()->user()->ordersPaid;

        $orders = $orders->map(function ($order) {

            $order->order_products = $order->order_products->map(function ($products) {
                $products['processedImgUrl'] = true;
                return $products;
            });

            return $order;
        });

        return response()->json(['flavor_orders' => $orders]);
    }