从 PHP 读取 json 响应并推送到 javascript 多维数组中

Reading json response from PHP and pushing into javascript multidimensional array

本文关键字:javascript 数组 读取 PHP json 响应      更新时间:2023-09-26
[
  {"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}
]

这是我从 php 脚本中得到的 json 响应。我需要在 javascript 中的多维数组中存储或推送它。我能够使用以下代码成功解码 json 响应。

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);
    }       
  });
});

我还需要在不同的函数中全局使用此值。

首先,

您希望将 undefined 的检查设置为"AND"条件,因为必须定义这两个条件,因为您必须定义它们,因为您正在访问它们并将它们都分配给"then"子句中的变量。

当你说"多维数组"时,如果它只有数字索引,你可以在javascript中拥有一个多维数组。相反,如果您想拥有键值对,它将是一个对象而不是数组。如果这对您来说足够好,只需每次推送一个数组,而不是将单个值推送到两个单独的数组:

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));
    }       
  });
});