Here is the JSON which is sent asynchronously to my php page. It is essentially a product list, which will be inserted into my mySQL database.
My issue is decoding the JSON in PHP. I can do this fine in js with the 'eval' function, but in PHP my efforts have resulted in a complicated series of explode and implode functions.
{
    "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"
        }
    ]
}
I know php has a built in json_decode function, but in the PHP documentation they only show how to handle an array.
Any advice or help is really appreciated
Taylor
If you call json_decode($data,true);, your data will be:
Array(
    "Product"=>Array(
        Array(
            "Product_Title"=>"Cloth",
            "Product_Description"=>"Here is cloth",
            "Price"=>"100",
            "Category_ID"=>"1"
        ),
        Array(
.............
        )
    )
);
What is wrong with that?
If you want to preserve the stdClass objects, you need to use the object-property syntax.
<?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'} . "
";
}
?>
Outputs:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With