如何在PHP中处理JSON?

Tay*_*Mac 5 php json

这是JSON,它以异步方式发送到我的php页面.它本质上是一个产品列表,将被插入到我的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"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我知道php有一个内置的json_decode函数,但在PHP文档中它们只显示了如何处理数组.

任何建议或帮助都非常感谢

泰勒

Nie*_*sol 10

如果您致电json_decode($data,true);,您的数据将是:

Array(
    "Product"=>Array(
        Array(
            "Product_Title"=>"Cloth",
            "Product_Description"=>"Here is cloth",
            "Price"=>"100",
            "Category_ID"=>"1"
        ),
        Array(
.............
        )
    )
);
Run Code Online (Sandbox Code Playgroud)

这有什么问题?


Jar*_*ish 5

如果要保留stdClass对象,则需要使用object-property语法.

<?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'} . "

";
}

?>
Run Code Online (Sandbox Code Playgroud)

输出:

Products:
Cloth
Here is cloth
100
1

Products:
Cloth
Here is cloth
100
1

Products:
Cloth
Here is cloth
100
1
Run Code Online (Sandbox Code Playgroud)

http://codepad.org/JxYAO5De