0

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
3
  • 1
    You can't use curly quotes in JSON. Commented Jan 8, 2016 at 23:46
  • 1
    Welcome 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. Commented Jan 8, 2016 at 23:50
  • The JSON data above has a comma after the lat value. This will break some JSON parsers. Commented Jan 9, 2016 at 0:08

2 Answers 2

1

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

i already tried that but it is only returning the first value? never gets through the next record.
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 "
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?
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...
0
 $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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.