这是以异步方式发送到我的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文档中它们只展示了如何处理数组。
非常感谢任何建议或帮助
泰勒
答案 0 :(得分:10)
如果您致电json_decode($data,true);
,您的数据将是:
Array(
"Product"=>Array(
Array(
"Product_Title"=>"Cloth",
"Product_Description"=>"Here is cloth",
"Price"=>"100",
"Category_ID"=>"1"
),
Array(
.............
)
)
);
这有什么问题?
答案 1 :(得分: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'} . "
";
}
?>
输出:
Products:
Cloth
Here is cloth
100
1
Products:
Cloth
Here is cloth
100
1
Products:
Cloth
Here is cloth
100
1