简体   繁体   中英

How to json encode this data in PHP?

I have the following code in my controller:

$regions = $this->signup_m->get_regions($country_id);
foreach ($regions as $key => $region) {
     echo "<option value='$key'>$region</option>";
}

It's being called by an ajax request. Instead of building out the html in the controller I rather return a json object back from which I can build out the dropdown options. How can I send this data in a json format?

I read about PHP's json_encode function and I am able to use it when I need to send back a single object but in this case I think I need to send back multiple objects (one for each dropdown option). So not sure how to go about it since it's all inside a loop.

in the php:

$regions = $this->signup_m->get_regions($country_id);
$jsonObj = array();
foreach ($regions as $key => $region) {
    $jsonObj[] = (object) array('value'=>$key, 'test'=>$region);
}
echo json_encode($jsonObj);

in the javascript you will receive a json object. if you are using jquery you're all set, just loop through the array. otherwise you'll have to parse/eval it and then loop through it

You could do it using less space as follows:

$keysRegionsJSON = json_encode($this->signup_m->get_regions($country_id));

Then you would consume that as follows:

$keysRegions = json_decode($keysRegionsJSON);
foreach ($keysRegions as $key => $region) {
    echo '<option value="' . $key . '">' . $region . '</option>';
}

The same thing in plain JS:

for (key in keysRegionsJS) {
    document.write('<option value="' + key + '"> + keysRegionsJS[key] + '</option>';
}

You can do it without json_encode as follows

$json="{";
$count=0;
$regions = $this->signup_m->get_regions($country_id);
foreach ($regions as $key => $region) {
    if($count>0){$json.=",";}
    $json.="\"".$key."\":\"".$region."\"";
    $count++;
}
$json.="}";
echo $json;

and then you'll use a for in loop in your javascript to turn that back into the options

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