How to handle JSON in PHP?

Here is the JSON that is being sent to my php page asynchronously. This is essentially a list of products that will be inserted into my mySQL database.

My problem is decrypting JSON in PHP. I can do this in js with the eval function, but in PHP my efforts led to a complex series of tear and unbind 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 that php has a built-in json_decode function, but in the PHP documentation they only show how to handle the array.

Any advice or help really appreciated

Taylor

+4
source share
2 answers

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?

+10
source

If you want to save stdClass objects, you need to use the syntax of the property object.

 <?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 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

+5
source

Source: https://habr.com/ru/post/1394734/


All Articles