0
`{
    "student": [{
        "name": "Alice",
        "rno": "187654"
    }]
}`

I am trying to get the value of rno using PHP code

`$data = json_decode($json, true);
 foreach ($data as $item) {
    $name = $item['name'] ;
    $number= $item['rno'] ;
}`
2
  • What is the error you're getting? Commented Apr 20, 2017 at 8:33
  • Possible duplicate of Access JSON values in PHP Commented Jul 31, 2017 at 5:22

3 Answers 3

2

@Sahil Gulati's code is more prefect and right way to parse the json in php

here is an other way to parse the json data in php

<?php

$data = json_decode($json, true);

foreach ($data as $item) {
    foreach ($item as $val) {
        echo $name = $val['name'];
        echo $number = $val['rno'];
    }
}

 ?> 

the above code that i have shared you can understand easily. but after learning that how to parse json data in php you should use @Sahil Gulati's mathod.

Sign up to request clarification or add additional context in comments.

Comments

1

Change this to:

foreach ($data as $item)

This:

foreach ($data["student"] as $item)

Try code snippet here

PHP code:

<?php

ini_set('display_errors', 1);
$data = json_decode($json, true);
foreach ($data["student"] as $item)
{
    $name = $item['name'];
    $number = $item['rno'];
}

Comments

0

You should take a closer look at the structure of the json encoded data. That helps to implement a clean iteration:

<?php
$input = <<<JSON
{
    "student": [{
        "name": "Alice",
        "rno": "187654"
    }]
}
JSON;
$data = json_decode($input);
$output = [];
array_walk($data->student, function($entry) use (&$output) {
    $output[] = $entry->rno;
});
print_r($output);

The output of above code obviously is:

Array
(
    [0] => 187654
)

The output format has been chosen as an array, since the json structure suggests that multiple students can be contained.


If you are only directly interested in the rno property of the first entry in the student array, then you can access it directly:

<?php
$input = <<<JSON
{
    "student": [{
        "name": "Alice",
        "rno": "187654"
    }]
}
JSON;
$data = json_decode($input);
var_dump($data->student[0]->rno);

The output of that variant obviously is:

string(6) "187654"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.