2011-11-09 62 views
0

我对JSON有点新,所以试图理解什么是最好的方式来做到这一点。我有两个变量:postcode和energyrating,我想放入JSON,然后解析为for循环。这个while循环的正确JSON结构是什么?

我可以让它与一个变量一起工作,但是当我有两个它不起作用。

这里是我的JSON:

header('Content-type: application/json'); 

$postcodeArray = array('postcodes' => array("E6 2JG","SE1 2AQ","DA1 1DZ"), 'energyrating' => array("A","B","C","D","E","F","G")); 

die(json_encode($postcodeArray)); 

这里是我的jQuery:

function addNew(postcodes) { 
if(postcodes.length > 0) { 
    for(var i = 0; i < postcodes.length; i++) { 

     var address = postcodes[i]; 
     var rating = energyrating[i]; 

     geocoder.geocode({ 'address': address }, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       map.setCenter(results[0].geometry.location); 

       var image = '../img/markers/' + rating + '.png'; 
       var marker = new google.maps.Marker({ 
        map: map, 
        position: results[0].geometry.location, 
        icon: image 
       }); 
      } else { 
       alert("Geocode was not successful for the following reason: " + status); 
      } 
     }); 
    } 
} else { 
    alert("Sorry, no data was found."); 
} 
} 

如何获得这与两个变量的工作?

+0

你的addNew()函数是如何调用的?另外,对于你显示的'postcodes'和'energyrating'数据是不同长度的数组,那么你怎样才能通过相同的for循环遍历两个数组? – nnnnnn

回答

0

什么不正确?

读你的代码,我会说你的代码有错误。该energyrating参数丢失到您的ADDNEW功能:

function addNew(postcodes, energyrating) { 

假设你打电话给你的功能是这样的:

addNew(jsonData.postcodes, jsonData.energyrating); 
0

使用JSON变量来存储数据这样的:

$postcodeArray = '{"postcodes":{"0":E6, "1":"2JG", "3":"SE1 2AQ","4":"DA1 1DZ"}, "energyrating":{"0":"A","1":"B","2":"C","3":"D","4":"E","5":"F","6":"G"}}'; 

代替

$postcodeArray = JSON.parse('postcodes' => array("E6 2JG","SE1 2AQ","DA1 1DZ"), 'energyrating' => array("A","B","C","D","E","F","G")); 

您可以访问这些值。

或者在函数addNew的第一行尝试json_decode(postcodes)