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

时间:2015-02-24 22:31:19

标签: php json angularjs

在下面的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中推动这个评论数据成为一个兄弟IN"评论"并针对它应该是的确切产品?我对PHP非常陌生,非常感谢您的指导!

1 个答案:

答案 0 :(得分:0)

如果我理解你的要求,这里你需要使用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'];
        ...
    }
}

希望有所帮助!

相关问题