使用PHP将对象推送到嵌套的JSON


Pushing object to nested JSON using PHP?

在下面的JSON对象中,我有两个伪产品和一组嵌套的互为兄弟的评论:

product.json

[
{
    "name": "Dodecahedron",
    "price": 2.95,
    "description": "This gem is awesome and has 10 sides.",
    "images": [
        {
            "full": "dodecahedron-01-full.jpg",
            "thumb": "dodecahedron-01-thumb.jpg"
        }
    ],
    "reviews": [
        {
            "stars": 5,
            "body": "I love this product!",
            "author": "joe@thomas.com"
        },
        {
            "stars": 1,
            "body": "This product sucks",
            "author": "tim@hater.com"
        }
    ]
},
{
    "name": "Hectahedron",
    "price": 8.95,
    "description": "Wonderful 6-sided gem that will please all.",
    "images": [
        {
            "full": "hectahedron-01-full.jpg",
            "thumb": "hectahedron-01-thumb.jpg"
        }
    ],
    "reviews": [
        {
            "stars": 4,
            "body": "product is awesome, seriously!",
            "author": "james@crazy.com"
        },
        {
            "stars": 2,
            "body": "Seriously sucks, would give 0 if i could",
            "author": "john@hater.com"
        }
    ]
}

]

我使用AngularJS将新创建的JS审查对象从HTML表单发送到PHP。但是,在PHP中,你如何将这些评论数据推送到"评论"中,并针对它应该在的确切产品?我是PHP的新手,非常感谢您的指导!

如果我理解你的要求,这里你需要使用json_decode()函数:

$productsRreviews = json_decode($_POST['reviews'], true);

这将给你一个PHP关联数组,你可以处理它来做任何你需要做的事情

foreach ($productsReviews as $productReviews) {
    $name = $productReviews['name'];
    $price = $productReviews['price'];
    $reviews = $productReviews['reviews'];
    foreach ($reviews as $review) {
        $stars = $review['stars'];
        ...
    }
}

希望能有所帮助!