在json中访问php数组元素

时间:2011-08-15 01:28:29

标签: php jquery ajax json

我从php返回一个数组数组到json

这是php数组

$cities = array();
while($row = mysql_fetch_array($result)){
    $cityRow= array('cityNo'=>$row['city_no'], 'cityName'=>$row['city_name']);
    $cities[]=$cityRow;
}   
echo json_encode($cities);

这是json

$.getJSON("controllers/Customer.controller.php",param,function(result){
    // what should I write here to reach the array elements??
});

2 个答案:

答案 0 :(得分:8)

您可以使用.each迭代对象:

$.getJSON("controllers/Customer.controller.php", param, function(json){

    // loop over each object in the array
    // 'i' is the index of the object within the array
    // 'val' (or this) is the actual object at that offset
    $.each(json, function(i, val) {
        console.log(val.cityNo); // same as this.cityNo
        console.log(val.cityName); // same as this.cityName
    });
});

答案 1 :(得分:0)

根据你可以做的documentation on jQuery

$.getJSON("controllers/Customer.controller.php",param,function(result){
    alert(result.cityNo);
    alert(result.cityName);
});