handling nested json in looping - php

json after json_encoded
{
"data":[
{
"name":"JIN",
"id":"100007934492797"
},
{
"name":"aris",
"id":"100008128873664"
},
{
"name":"Madm",
"id":"34234234"
}
],
"paging":{
"next":"https://graph.facebook.com/v1.0/1380314981/friends?limit=5000&offset=5000&__after_id=enc_AeyRMdHJrW0kW9vIZ41uFPXMPgE-VwRaHtQJz2JWyVc0hMl9eOG10C6JWjoCO8O2E4m24EPr28gIt9mxQR8oIQmN"
}
}
I want to store the name and ID of my json in db. But when I use for loop there's a problem with the offset, I suspect it's the last part of the json. How to remove the paging part? I tried
foreach($friends as friend){
echo friend[0]->name;
}

First, your original code would never work:
foreach($friends as friend){
echo friend[0]->name;
}
Those references to friend should have $ in front of them making them $friend. Then to solve your larger issue, just use a nested foreach loop:
$json = <<<EOT
{
"data": [
{
"name": "JIN",
"id": "100007934492797"
},
{
"name": "aris",
"id": "100008128873664"
},
{
"name": "Madm",
"id": "34234234"
}
],
"paging": {
"next": "https://graph.facebook.com/v1.0/1380314981/friends?limit=5000&offset=5000&__after_id=enc_AeyRMdHJrW0kW9vIZ41uFPXMPgE-VwRaHtQJz2JWyVc0hMl9eOG10C6JWjoCO8O2E4m24EPr28gIt9mxQR8oIQmN"
}
}
EOT;
$friends = json_decode($json);
foreach($friends as $friend_data){
foreach($friend_data as $friend){
echo $friend->name . '<br />';
}
}
And the output of this would be:
JIN
aris
Madm
Additionally, if working with arrays makes more sense for you, you can always set json_decode to return an array by setting the second parameter to true. Here is refactored code as an example:
$friends = json_decode($json, true);
foreach($friends as $friend_data){
foreach($friend_data as $friend_key => $friend_value){
if (isset($friend_value['name'])) {
echo $friend_value['name'] . '<br />';
}
}
}

Related

How to access array inside document using PHP [duplicate]

This question already has answers here:
Get data from JSON file with PHP [duplicate]
(3 answers)
Closed 6 years ago.
I want print specific vars from array inside a document.
JSON structure:
{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
},
etc
]
}
}
I am trying to do this in PHP (and already decoded that json). How can I access and print all ids using foreach or for?
I can not understand how I can manage "return" scope.
You can decode the json contents and use it like an array. This should work:
$json = json_decode($string, true);
$contacts = $json['return']['contacts'];
foreach($contacts as $contact){
echo $contact['contact']['id'];
}
Json decode to array:
$json = json_decode($strjson, true); // decode the JSON into an associative array
and
echo "<pre>";
print_r($json);
And foreach:
foreach ($json as $key => $value) {
echo $key . " ". $value. "<br>";
}
Working example:
$json = '{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
}
]
}
}';
$json = json_decode($json, true);
print_r($json);
foreach ($json['return']['contacts'] as $val) {
echo $val['contact']['id']."<br>";
}
Try this code:
$json ='
{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
},
etc
]
}
}
';
$array = json_decode($json,TRUE);
foreach($array['return']['contacts'] as $value ){
echo $value['id'];
}
Use file_get_contents function if you want to pull data from file.

How to parse json array using php foreach?

I want to get id,url,img and title of videos in the JSON data.My current code doesn't output anything
could any one tell me what i am doing wrong.Thanks
$code2 = stripslashes($_POST['outputtext']);
$data = json_decode($code2, true);
$i = 0;
foreach($data->videos as $values)
{
echo $values->id . "\n";
echo $values->url . "\n";
echo $values->img . "\n";
echo $values->title . "\n";
$i++;
}
data:
{
"cat": {
"id": "1234567",
"source_id": null,
"title_en": "first season",
"description_en": "This is spring category ",
},
"videos": [{
"id": "312412343",
"url": "\/2015-07-17\/1abcd.mp4",
"img": "image\/44\/\/2015-07-17\/1abcd.jpg",
"title": "first",
}, {
"id": "2342343",
"url": "\/2015-07-16\/2dcdeg.mp4",
"img": "images\/44\/\/2015-07-16\/2dcdeg.jpg",
"title": "second",
}];
}
validated json data:
{
"cat":{
"id":"1234567",
"source_id":null,
"title_en":"first season",
"description_en":"This is spring category "
},
"videos":[
{
"id":"312412343",
"url":"\/2015-07-17\/1abcd.mp4",
"img":"image\/44\/\/2015-07-17\/1abcd.jpg",
"title":"first"
},
{
"id":"2342343",
"url":"\/2015-07-16\/2dcdeg.mp4",
"img":"images\/44\/\/2015-07-16\/2dcdeg.jpg",
"title":"second"
}
]
}
Because you call
$data = json_decode($code2, true);
your $data is an array and not an object as you try to access it. So either access it as regular array, or change 2nd argument of json_decode() to false (or removeit as this is default), as this is what controls conversion behavior.
See docs: http://php.net/manual/en/function.json-decode.php
Your data is not a valid JSON (; at the end, redundant and missing comas - it's simply broken).
In case of such problems, var_dump() is pretty helpful to inspect what data you are really working with.

how to convert this malformed string to json with php/jquery

I have this string -
{
'Carlos':
{
Name: 'Spers',
href: "http://google.com"
},
'Winter':
{
Name: 'Warres',
href: "http://yahoo.com"
},
'Doer':
{
Name: 'Pinto',
href: "http://carpet.com"
}
}
I validated the with JSLinter, it say invalid with multiple errors. And I understand that. The issue is, this is what I get from a third party service. I have to leave with it. Now I'm stuck with it to convert into JSON object to work with it.
When I use json_decode($thisStirng) in PHP, it returns null. $.parseJSON(data) returns me errors too.
I would like to show the data on the webpage with some styling. So at the end, I want json object at the client to work with. So converting data to JSON with PHP or jQuery, anyway would work.
How should I go about it?
Update
I got an associative array with json_decode($thisStirng, true). Now I want echo it as a string so that on browser, I could access it with array indexes.
Thank you all - got it working as below -
$someObject = json_decode($thisStirng,true);
$myarry = array();
foreach ($someObject as $key => $val) {
$temparray = array();
$temparray[]= $key;
$temparray[]= $val;
$myarry[]= $temparray;
}
echo json_encode($myarry);
Now in jQuery I can access, data[index][0] as 'Carlos' and other dynamic keys. data[index][1] is an object with 'Name' and 'href' properies.
You can try this code.
$jsonData='{
"Carlos":
{
"Name": "Spers",
"href": "http://google.com"
},
"Winter":
{
"Name": "Warres",
"href": "http://yahoo.com"
},
"Doer":
{
"Name": "Pinto",
"href": "http://carpet.com"
}
}';
$arr1=array();
$arr2=array();
$arr3=array();
$phpArray = json_decode($jsonData, true);
foreach ($phpArray as $key => $value) {
$arr1=array();
$arr1[]=$key;
foreach ($value as $k => $v) {
$arr2=array();
$arr2[$k]=$v;
$arr3[]=$arr2;
}
}
echo $arr3[0]['Name'];
try using this:
<?php
$jsonData='{
"Carlos":
{
"Name": "Spers",
"href": "http://google.com"
},
"Winter":
{
"Name": "Warres",
"href": "http://yahoo.com"
},
"Doer":
{
"Name": "Pinto",
"href": "http://carpet.com"
}
}';
$phpArray = json_decode($jsonData, true);
foreach ($phpArray as $key => $value) {
echo "Key:".$key. ", Name:". $value['Name'].'<br>';
}
?>
OUTPUT:
Key:Carlos, Name:Spers
Key:Winter, Name:Warres
Key:Doer, Name:Pinto

How to Parse JSON with PHP?

I can do a var_dump, but when trying to access the values, I am getting errors about the values not being found.
{
"metrics": {
"timers": [
{
"name": "com.android.timer.launchtime",
"startTime": 1232138988989,
"duration_ms": 1900
},
{
"name": "com.android.timer.preroll-load-time",
"startTime": 1232138988989,
"duration_ms": 1000
}
]
}
}
I used the following so far to try and parse it.
$json_file = file_get_contents('test.json');
$json_a = json_decode($json_file,true);
var_dump(json_decode($json_file)); //This works
echo $json_a['name']; //I want to print the name of each (from timers).
Try:
$yourDecodedJSON = json_decode($yourJson)
echo $yourDecodedJSON->metrics->timers[0]->name;
Or you can:
$yourDecodedJSON = json_decode($yourJson, true); // forces array
echo $yourDecodedJSON['metrics']['timers'][0]->name;
In your case, you may want to..
foreach($yourDecodedJSON['metrics']['timers'] as $timer){
echo $timer['name']; echo $timer['duration_ms']; // etc
}
If something fails, use:
echo json_last_error_msg()
To troubleshoot further
You need do it in following manner:-
<?php
$data = '{
"metrics": {
"timers": [
{
"name": "com.android.timer.launchtime",
"startTime": 1232138988989,
"duration_ms": 1900
},
{
"name": "com.android.timer.preroll-load-time",
"startTime": 1232138988989,
"duration_ms": 1000
}
]
}
}';
$new_array = json_decode($data); //convert json data into array
echo "<pre/>";print_r($new_array); //print array
foreach ($new_array->metrics->timers as $new_arr){ // iterate through array
echo $new_arr->name.'<br/>'; // rest you can do also same
}
?>
Output:- https://eval.in/407418

read json like facebook json php

i try to read json by php
{
"data": [
{
"id": "3043252fsdgdf36360354",
"name": "name1",
"access_token": "CAAIf3VEtVSoBAHrVxHL16zt4H5OvwBmdfgs4F3auPE0NZBx5PmIujBAdqw0Cv4bZACXytT1O1y6FHEZA25E1aqQZD"
},
{
"id": "3326848fdgsdfgsdf03424168",
"name": "name2",
"access_token": "CAAIf3VEtVSoBAJinePVdfgsdfgMxuY3zaj9AimaoKx7VIO9jCqZCHC6ZBixL1n6ZC72LTMn0ZB4T8rOHD27WmzbBVgvUwgspeEZD"
}}
i try by this code
$sfgsdfg= $json_a=json_decode($read,true);
echo $json_a['data'][3043252fsdgdf36360354];
echo $json_a['3043252fsdgdf36360354'][access_token];
not working with this php code i need help to read it
i need select access_token by 3043252fsdgdf36360354 as echo $json_a['data'][3043252fsdgdf36360354]['access_token'];
i need only read by id as . mysql command . select access_token where id ='3326848fdgsdfgsdf03424168';
First of all, your JSON is missing a ] character and will cause json_decode to return NULL. You should first correct the JSON string. You can use a online service such as jsonlint.com to validate the JSON. Once you've decoded the JSON string as an associative array, you can just loop through the array and check if it contains the given ID in it. If it does, you can grab the corresponding access token easily.
I've made this into a short little function. You can use that to get the access token by ID:
$jsonArray = json_decode($str, TRUE);
function getAccessTokenFromID($id, $jsonArray) {
foreach ($jsonArray['data'] as $k => $elem) {
if($elem['id'] == $id) {
$access_token = $elem['access_token'];
}
}
return $access_token;
}
Usage:
$myid = '3043252fsdgdf36360354';
$my_accesstoken = getAccessTokenFromID($myid, $jsonArray);
Demo!
Isn't well formed json.
Try with:
{
"data": [
{
"id": "3043252fsdgdf36360354",
"name": "name1",
"access_token": "CAAIf3VEtVSoBAHrVxHL16zt4H5OvwBmdfgs4F3auPE0NZBx5PmIujBAdqw0Cv4bZACXytT1O1y6FHEZA25E1aqQZD"
},
{
"id": "3326848fdgsdfgsdf03424168",
"name": "name2",
"access_token": "CAAIf3VEtVSoBAJinePVdfgsdfgMxuY3zaj9AimaoKx7VIO9jCqZCHC6ZBixL1n6ZC72LTMn0ZB4T8rOHD27WmzbBVgvUwgspeEZD"
}
]
}
And php:
$val = json_decode($read, TRUE);
echo $val['data'][0]['id'];
UPDATED:
function find_by_id($id, $val) {
foreach($val['data'] as $key => $obj) {
if ($obj['id'] === $id)
return $obj['access_token'];
}
}

Categories