Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reach php array elements in json

I return an array of array from php to json

here's php array

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

Here's the json

$.getJSON("controllers/Customer.controller.php",param,function(result){
    // what should I write here to reach the array elements??
});
like image 634
palAlaa Avatar asked Dec 30 '25 11:12

palAlaa


1 Answers

You can iterate over the object using .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
    });
});
like image 99
karim79 Avatar answered Jan 02 '26 00:01

karim79



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!