在这种情况下,构建JSON数组最聪明的方法是什么?

I'm using codeigniter php framework and select2 jquery plugin.

I want to load all the names stored in my database with its id so I use a a query like this:

select id, name from drivers;

Then I format the result returned by this way:

$data = array()

foreach ($query->result_array() as $row){
    $data[$row["id"]] = $row["name"];
}

return $data;

After that, I print the array encoded in JSON, and it's recieved by ajax. In the jquery I do something like this:

var html_res = "<option></option>";

$.each(data_json, function(key, value){
    html_res += "<option value='" + key + "'>" + value + "</option>";
});

$("#my-select2").html(html_res);

It works, but I'm really interesed in if there is a eficient/simplest way to get the same result.


Also I have another little question: Now I have a query like above:

select id, name, age from drivers;

And I want to load the content in a select2 plugin in two diferents <optgroup>:

  • The first will contain the drivers with age > 50.
  • The last one the drives with age < 50.

But I don't know what is the best practice in this case to structure the associative array in php, and after, load it in select2 using $.each function.

Could you tell me how you do this? I've only come up with that solution for the first question (don't know if is the best). But I'm afraid I've got no one for the second one.

Any tip, help or advice will be appreciated, and if you need more info, let me know and I'll edit the post.

Something like:

PHP

$data = array(
    "under 50" => array(),
    "over 50" => array()
);

foreach ($query->result_array() as $row){
    $el = array(
        "name" => $row["name"],
        "age" => $row["age"]
    );
    if ($row["age"] < 50) {
        $data["under 50"][$row["id"]] = $el;
    } else {
        $data["over 50"][$row["id"]] = $el;
    }
}

return $data;

JS

var html_res = "<optgroup><option></option>";

$.each(data_json["under 50"], function(key, row){
    html_res += "<option value='" + key + "'>" + row.name + "</option>";
});
html_res += "</optgroup><optgroup>"
$.each(data_json["over 50"], function(key, row){
    html_res += "<option value='" + key + "'>" + row.name + "</option>";
});
html_res += "</optgroup>";

$("#my-select2").html(html_res);

You don't strictly need to send the age, but this is how you could extend your list of drivers. Also, you need the query the age, obviously.