简体   繁体   中英

how to use json_encode function of an array

I would like to select a specific line of an object that have been created using json_encode function from a php array.

  while($locations=$req->fetch()){ $t = $locations->titre; $la = $locations->latitude; $lo = $locations->longitude; $typ = $locations->type; $ep = $locations->couleur; $matrice[$i] = array($t, $la, $lo, $ep); $i=$i+1; } 

 var locations = <?php echo json_encode($matrice); ?>; locations[0] = ['ma position actuelle', 0, 0, 0]; //console.log(Object.keys(locations)); //console.log(locations); var centerLat=0.0, centerLong=0.0; for (var i=1; i<Object.keys(locations).length; i++) { centerLat+=locations[i][1]; centerLong+=locations[i][2]; } 

I would like to select the second and the third element of "locations" but the syntax inside the loop is wrong. Does anyone has an idea. Thank you

First you should do:

var locations = JSON.parse(<?php echo json_encode($matrice); ?>);

Then console.log(locations.toString()); to check your data

After, I think you're looking for Array.prototype.unshift() to add elements at the beginning of the array:

locations.unshift(['ma position actuelle', 0, 0, 0]);

( locations[0] = ['ma position actuelle', 0, 0, 0] just replace first item of the array)

then change you for loop

for (var i=1; i<Object.keys(locations).length; i++)

for

var i = 1, ln = locations.length;
for (i;i<ln;i++)

You can access any item in an JSONArray (or any Array) in JS like this:

object[i]

In your example, if you wanna get the second and third element:

for (...) {
  var longitude = locations[i][1];
  var latitude = locations[i][2];
}

But, I suggest that you use keys and make JSONObjects instead of just JSONArrays, like this:

  $locations = array();

  while($locations=$req->fetch()){

    $location = array(
      'titre' => $locations->titre,
      'latitude' => $locations->latitude,
      'longitude' => $locations->longitude,
      ... etc
    );

    $locations[] = $location;

  }

That way you'll end up with a nice JSONArray filled with JSONObjects and you can call them from JS like this:

//locations is a JSONArray
var locations = <?php echo json_encode($matrice); ?>; 
//locations[0] is a JSONObject
var latitude = locations[0].latitude;
var latitude = locations[0].longitude;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM