I have a json structure like this
[
{
"id" : 1,
"user_id" : 1,
"location" : {
"long" : 34.2489234,
"lat" : -117.234234,
},
"active" : 1
}, {
"id" : 2,
"user_id" : 2,
"location" : {
"long" : 34.245234234,
"lat" : -116.23786834,
},
"active" : 1
}, {
"id" : 3,
"user_id" : 3,
"location" : {
"long" : 34.245634234,
"lat" : -114.237787834,
},
"active" : 0
}
]
how can i loop through the data so i would only get the location "long" and "lat"?
asked Jan 8, 2016 at 23:40
-
1You can't use curly quotes in JSON.Barmar– Barmar2016年01月08日 23:46:40 +00:00Commented Jan 8, 2016 at 23:46
-
1Welcome to StackOverflow. Check the StackOverflow's help on asking questions first, please. Focus on How to ask a good question and How to create a Minimal, Complete, and Verifiable example, but also other help topics would be useful.David Ferenczy Rogožan– David Ferenczy Rogožan2016年01月08日 23:50:38 +00:00Commented Jan 8, 2016 at 23:50
-
The JSON data above has a comma after the lat value. This will break some JSON parsers.RCrowt– RCrowt2016年01月09日 00:08:58 +00:00Commented Jan 9, 2016 at 0:08
2 Answers 2
Start by decoding the json-string:
$data = json_decode($the_json_string);
This will give you a php-array with objects which you can loop through like usual:
foreach($data as $obj) {
echo $obj->location->long;
echo $obj->location->lat;
}
answered Jan 8, 2016 at 23:46
4 Comments
CuriousDev
i already tried that but it is only returning the first value? never gets through the next record.
M. Eriksson
Then show what you have done... I can't debug your code if I don't get to see it. What I wrote does work.. however.. you have errors in your JSON-string... you need to remove the comma after the
"lat"
parameters (in PHP.arrays this is allowed but not in JSON) and replace the curly quotes with standard "
CuriousDev
oh, i just manually typewritten those json string from my multiple nested json data - my apologies. so basically it is a wp_remote_get request and my for loop script is similar to yours but it is just displaying 1 record and cant get throug next. any workaround?
M. Eriksson
Similar isn't the same.. update your question with what you have tried... you haven't given us anything to go with here... the json isn't a copy of the actuall json-string, you haven't shown the code you tried... we're not psycics...
$data = json_decode($json,true);
foreach ($data as $obj ){
echo $obj['location']['long'];
echo $obj ['locaion']['len'];
}
I hope this will work
answered Jan 9, 2016 at 11:54
Comments
lang-php