Help pass multilevel php array to Javascript
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

Hi people

I need your help with this code. I'm stuck. This sample Google API code

has a Javascript locations array var locations = [...];

I have tried the following code to replace the Javascript array in vain with PHP.

What am I doing wrong?

$strmarkers[0] = array("lat: -1.275292" => 'lng: 36.812072'); $strmarkers[1] = array("lat: -1.282243" => 'lng: 36.815677'); $strmarkers[2] = array("lat: -1.273801" => 'lng: 36.825859');


var mynewlocations = [ <?php echo json_encode($strmarkers); ?> ]

@kostasx have solved it right, i want to thank you for the link you have post in the bounty. very helpful.
Chlegou 1 year ago

Crowdsource coding tasks.

2 Solutions

Winning solution

$strmarkers[0] = array(
  'lat' => -1.275292,
  'lng' => 36.812072
$strmarkers[1] = array(
  'lat' => -1.282243,
  'lng' => 36.815677

$strmarkers[2] = array(
  'lat' => -1.273801,
  'lng' => 36.825859


var mynewlocations = <?php echo json_encode($strmarkers, JSON_NUMERIC_CHECK); ?>

Results in:

var mynewlocations = [{"lat":-1.275292,"lng":36.812072},{"lat":-1.282243,"lng":36.815677},{"lat":-1.273801,"lng":36.825859}]
Thanks for the solution!
jobokoth 1 year ago
You're welcome. :)
kostasx 1 year ago
Hi Kostasx,not to push it but just to ask, how would the same work on this ? Its not working as in the other link....
jobokoth 1 year ago
Can you paste the code of what you are trying to achieve?
kostasx 1 year ago
Hi Kistasx, thanks, I actually got a way to sort out the linechart code. Thanks so much for your willingness to help.
jobokoth 1 year ago

The problem is, you're not assigning an attribute to a value, instead you are marking with (") all the stuff inside the JSON you want to put, so you're bassically telling ALL the JSON values to be an array of strings.

Instead, you should assign an attribute name (in this case, "lat", to (=>) a value -1.275292)

The correct way should be:

$strmarkers[0] = array("lat" => -1.275292, "lng" => 36.812072);

Thanks for the info!
jobokoth 1 year ago
View Timeline