简体   繁体   中英

Reading json response from PHP and pushing into javascript multidimensional array

[
  {"type":"1","text":"success"},
  {"yid":"167","uid":"15","lat":"13.0501383","lng":"77.597593","time":"2014-10-20 20:25:27","dist":1.95},
  {"yid":"204","uid":"32","lat":"13.0412773","lng":"77.6133699","time":"2014-11-17 03:15:24","dist":0.06}
]

This is my json response from php script. I need to store or push this in a multidimensional array in javascript. I'm able to decode the json response successfully using the below code.

var myLatLng = [];
var myYid = [];

post_data = {'userLat':position.coords.latitude, 'userLng':position.coords.longitude};

$.post('leo.php', post_data, function(response){
  $.each(response, function(index, element) {
    if(element.lat!=undefined || element.lng!=undefined)
    {
      myLatLng.push(element.lat+', '+element.lng);
      myYid.push(element.yid);
    }       
  });
});

I also need to use this values globally across different functions.

First of all you'll want your check for undefined to be an "AND" condition, because both will have to be defined seeing that you're accessing both of them and assigning both of them to a variable in your "then" clause.

When you say "multidimensional array", you can have a multidimensional array in javascript if it only has numerical indexes. If instead you want to have key-value pairs, it will be an object and not an array. If that is good enough for you, just push an array each time instead of pushing single values to two separate arrays:

var multiDimArray = [];

post_data = {'userLat':position.coords.latitude, 'userLng':position.coords.longitude};

$.post('leo.php', post_data, function(response){
  $.each(response, function(index, element) {
    if(element.lat!==undefined && element.lng!==undefined)
    {
      multiDimArray.push(new Array(element.lat+', '+element.lng,element.yid));
    }       
  });
});

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