Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning identifier/name to JSON object in PHP

I'm grabbing data from a mysql database and encoding a JSON object with PHP to use in JS. On the PHP end, I did this

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 the data in JS using jQuery, and I made an array to save the JSON data:

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

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

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

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

The problem is my JSON objects aren't called jmarkers or anything else, they have this generic 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 the PHP JSON encode function and I can't see where to set or change the object name. Any suggestions? Thank you!

like image 314
zannah Avatar asked Jan 16 '23 02:01

zannah


2 Answers

That's to be expected. JSON is essentially the right-hand-side of an assignment operation:

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

The x part is not included, since that's simply the name of the object. If you want your jmarkers text included, it'll have to be part of the data structure you're going to encode:

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

But all this does is add another layer to your data structure for no useful reason.

like image 90
Marc B Avatar answered Jan 18 '23 23:01

Marc B


$jmarkers is simply the identifier on the PHP side for the JSON object. When it gets passed, it converts the array value into a JSON-encoded string and therefore loses the identifier as a result.

In your PHP code at the moment, array_push($json, $jmarkers) is appending an array to your current $json array. You are therefore instancing a two-dimensional array, which will not be retrievable by the jmarkers identifier in your Javascript code. Simply retrieve the data using myMarkers[i] instead.

like image 33
Daniel Li Avatar answered Jan 18 '23 23:01

Daniel Li