-3

Want to parse JSON object array using PHP, but I don't know how to do it as I am new to PHP.

Here is my JSON (Structure can't be altered since the JSON is constructed by other system):

[
{
"animalName":"Fox",
"animalId":"1"
},
{
"animalName":"Elephant",
"animalId":"2"
},
{
"animalName":"Monkey",
"animalId":"3"
},
{
"animalName":"Donkey",
"animalId":"4"
}
]

I used json_decode function to decode it but I dont know how to read values inside the json.

For ex: How would I get the value Monkey by parsing the JSON.

Thanks in advance for your help!

2 Answers 2

5

This will do it

$data = json_decode($json);

$data[0]->animalName; // "Fox"

Per a useful comment

<pre>
<?php print_r($data);
2
  • 1
    You can also do print_r("<pre>" . $data . "</pre>", true); to make it nicely formatted while showing the whole thing :) Commented Apr 5, 2014 at 8:46
  • Thanks for the answer. When I have the JSON as hardcoded one, I am able to decode it, But when I am trying to decode JSON that I am getting via HTTP post, it is not working. PHP code is here: <?php $json = $_POST["animaljson"]; //$json = '[{"animalName":"Fox","animalId":"1"},{"animalName":"Fox","animalId":"1"}]'; $data = json_decode($json); echo $data[0]->animalName; ?> Please suggest if I miss something here. Commented Apr 5, 2014 at 9:21
1

If you want to get all in a loop you can do as

$str='[
{
"animalName":"Fox",
"animalId":"1"
},
{
"animalName":"Elephant",
"animalId":"2"
},
{
"animalName":"Monkey",
"animalId":"3"
},
{
"animalName":"Donkey",
"animalId":"4"
}
]';

$data = json_decode($str,true);

foreach($data as $k=>$v){
 echo "Animal Name :".$v["animalName"]."<br />";
  echo "Animal ID :".$v["animalId"]."<br />";
}
2
  • Thanks for the answer. When I have the JSON as hardcoded one, I am able to decode it, But when I am trying to decode JSON that I am getting via HTTP post, it is not working. PHP code is here: <?php $json = $_POST["animaljson"]; //$json = '[{"animalName":"Fox","animalId":"1"},{"animalName":"Fox","animalId":"1"}]'; $data = json_decode($json); echo $data[0]->animalName; ?> Please suggest if I miss something here. Commented Apr 5, 2014 at 9:24
  • can u try $json = file_get_contents('php://input'); instead of POST and then decode that. Commented Apr 5, 2014 at 10:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.