Assigning an id / name to a JSON object in PHP

I collect data from a mysql database and encode a JSON object with PHP for use in JS. At the end of PHP I did it

while ($ row = mysql_fetch_array ($ result))

{ $jmarkers = array( 'id'=> $row['id'], 'lat' => $row['lat'], 'lng' => $row['lng'], etc... ); array_push($json, $jmarkers); } $jsonstring = json_encode($json); echo $jsonstring; 

I can access data in JS using jQuery and I created an array to store JSON data:

$. getJSON ("getjson.php", function (data)

 { myMarkers = data; console.log(myMarkers); }); 

I planned to access the data in the myMarkers array inside the loop, with a suggestion like this:

var tempLat = myMarkers.jmarkers [i] .lat;

The problem is that my JSON objects are not called jmarkers or anything else, they have this common name "Object" when I print them to the console:

Object {id = "2", lat = "40.6512", lng = "- 73.9691", more ...},

So I'm not sure how to point to them in my JS array. I looked at the PHP JSON encoding function, and I do not see where to set or change the name of the object. Any suggestions? Thanks!

+4
source share
3 answers

What to expect. JSON is essentially the right side of an assignment operation:

 var x = {'foo':'bar'}; ^^^^^^^^^^^^^---- JSON 

Part x not included, as this is just the name of the object. If you want your jmarkers text jmarkers be included, it must be part of the data structure that you are going to encode:

 $arr = array( 'jmarkers' => array(...your data here...); ); 

But all this makes adding another layer to your data structure for no good reason.

+5
source

$jmarkers is just an identifier on the PHP side for the JSON object. When it is passed, it converts the value of the array to a string encoded in JSON, and therefore loses the identifier as a result.

In your PHP code, currently array_push($json, $jmarkers) adds an array to your current $json array. This way you create a two-dimensional array that will not be restored by the jmarkers identifier in your Javascript code. Just load the data using myMarkers[i] .

+3
source

You are not. All this is an object. You only need to access the elements inside.

 alert(myMarkers.id); 
+1
source

All Articles