首页 > 解决方案 > Laravel 访问控制器中的 JSON 对象

问题描述

在提交的表单保存在变量中后,我在控制器中有这个数组$product

[
    {
        "id": 2,
        "name": "nancy",
        "cost": 34,
        "quantity": 0,
        "barcode": 12345,
        "category_id": 2,
        "created_at": "2020-07-05T16:04:10.000000Z",
        "updated_at": "2020-07-09T04:06:09.000000Z"
    },
    {
        "id": 5,
        "name": "jk",
        "cost": 100,
        "quantity": 2,
        "barcode": 147258,
        "category_id": 2,
        "created_at": "2020-07-08T20:34:56.000000Z",
        "updated_at": "2020-10-18T13:09:16.000000Z"
    }
]

如何访问对象中的属性,如id, name, barcode

标签: laravel

解决方案


只需解码它,使用json_decode

$products = json_decode($products, true);  // When TRUE, JSON objects will be returned as associative arrays

foreach($products as $product){
    echo $product['id']; 
}

推荐阅读