如何在PHP中处理JSON?

6
这��我异步发送给php页面的JSON数据。它基本上是一个产品列表,将被插入到我的MySQL数据库中。
我的问题是在PHP中解码JSON。使用“eval”函数可以在js中轻松完成此操作,但在PHP中,我的努力导致了一系列复杂的分裂和合并函数。
{
    "Product": [
        {
            "Product_Title": "Cloth",
            "Product_Description": "Here is cloth",
            "Price": "100",
            "Category_ID": "1"
        },
        {
            "Product_Title": "Cloth",
            "Product_Description": "Here is cloth",
            "Price": "100",
            "Category_ID": "1"
        },
        {
            "Product_Title": "Cloth",
            "Product_Description": "Here is cloth",
            "Price": "100",
            "Category_ID": "1"
        }
    ]
}

我知道php有内置的json_decode函数,但在PHP文档中只展示了如何处理数组。如果您有任何建议或帮助,我们将不胜感激。
谢谢, Taylor

你可以这样做:$json_decoded->{'Product'}[0]->{'Product_Title'}; - Jared Farrish
@JaredFarrish:$json_decoded->{'Product'} 不等同于 $json_decoded->Product 吗?编辑:是的 http://codepad.org/fGzAZk7v 尽管我仍然更喜欢关联数组。 - mpen
@Mark - 是的,那只是之前尝试的遗物。 - Jared Farrish
将数据库值转换为JSON数据。观看这些视频... http://www.youtube.com/watch?v=EvFXWqEqh6o - user3612872
2个回答

11
如果你调用json_decode($data,true);,你的数据将会是:
Array(
    "Product"=>Array(
        Array(
            "Product_Title"=>"Cloth",
            "Product_Description"=>"Here is cloth",
            "Price"=>"100",
            "Category_ID"=>"1"
        ),
        Array(
.............
        )
    )
);

那个有什么问题吗?


6
如果您想保留 stdClass 对象,您需要使用对象属性语法。
<?php

$json = '{
    "Product": [
        {
            "Product_Title": "Cloth",
            "Product_Description": "Here is cloth",
            "Price": "100",
            "Category_ID": "1"
        },
        {
            "Product_Title": "Cloth",
            "Product_Description": "Here is cloth",
            "Price": "100",
            "Category_ID": "1"
        },
        {
            "Product_Title": "Cloth",
            "Product_Description": "Here is cloth",
            "Price": "100",
            "Category_ID": "1"
        }
    ]
}
';

$json_decoded = json_decode($json);

// Note, it's usually a bad idea to use use count() like this;
// cache the count before the for() in a variable and use that.
// This is for demo purposes only. :)
for ($i = 0; $i < count($json_decoded->{'Product'}); $i++) {
    echo "Products:
" . $json_decoded->{'Product'}[$i]->{'Product_Title'} . "
" . $json_decoded->{'Product'}[$i]->{'Product_Description'} . "
" . $json_decoded->{'Product'}[$i]->{'Price'} . "
" . $json_decoded->{'Product'}[$i]->{'Category_ID'} . "

";
}

?>

输出:

Products:
Cloth
Here is cloth
100
1

Products:
Cloth
Here is cloth
100
1

Products:
Cloth
Here is cloth
100
1

http://codepad.org/JxYAO5De


哈哈,我能不能指出这样说的讽刺意味:“// 注意,像这样使用count()通常是不好的…”,而实际上用正确的方法会更容易。因为人们愚蠢地根据简单性、简洁性或演示目的采取捷径,所以我在编辑时经常发现自己这样做。 - chacham15
或者,这是一个展示如何 通常 不要这样做并采取主动的机会去 不要这样做的方式。有些人会看到更好的方法(通常),但仍然会退回到更 简单 的方法。 - Jared Farrish

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接