Reputation: 203
i want to access value of country_id and country_name from this decoding string by json_decode() but it's not working my decoded data is priting by print_r() is given below:
{"country_Data":
[
{"country_id":"1","country_name":"India"},
{"country_id":"2","country_name":"Saudi Arabia"},
{"country_id":"3","country_name":"UAE"}
]
}
i tried like
foreach($data['country_Data'][0]['country_id'])
but no luck.please help thanks in advance
Upvotes: 1
Views: 289
Reputation: 203
`$data = '{"country_Data":[{"country_id":"1","country_name":"India"},
{"country_id":"2","country_name":"Saudi Arabia"},
{"country_id":"3","country_name":"UAE"}]}';
$json = json_decode($data,true);
foreach($json as $res)
{
foreach($res as $key => $value)
{
$datavalue[]=$value;
}
}
//print_r($datavalue);
foreach($datavalue as $v)
{
echo $v['country_name'].'<br />';
}
`
Upvotes: 0
Reputation: 79
//Your json encoded string
$string = '{"country_Data": [{"country_id": "1","country_name": "India"},{"country_id": "2","country_name": "Saudi Arabia"},{"country_id": "3","country_name": "UAE"}]}';
//your data decoded in an array
$arr = json_decode($string,true);
foreach($arr as $item)
{
foreach($item as $value){
print_r($value['country_id']." ".$value['country_name']."\n");
}
}
//Printed data
1 India
2 Saudi Arabia
3 UAE
Upvotes: 1
Reputation: 20445
try this
$data = json_decode($json_data, true);
foreach($data as $cd) {
print_r($cd);
echo $cd['country_id'] .', '. $cd['country_name'];
}
Upvotes: 0
Reputation: 12504
Use the for loop like this
$data = json_decode($json_data, true); // 2nd param converts output to associative arrays
foreach($data['country_Data'] as $country_data) {
print_r($country_data);
echo $country_data['country_id'] .', '. $country_data['country_name'];
}
Upvotes: 1
Reputation: 571
since json_decode creates an object from your data (by default) you need to acces it as a property:
like this:
foreach($countryArray->country_Data as $row) {
echo $row->country_id;
}
or use the loop the other guys suggested but you need to make sure json_decode gives back an array, you can do this setting the second parameter to true,
$countryArray = json_decode($jsonString, true);
Upvotes: 0
Reputation: 31225
Did you decode the $data json first?
$data = json_decode($json)
foreach($data['country_Data'] as $row) {
print_r($row);
}
Upvotes: 1