0

这是我所拥有的:

public function get_model_by_make($make = null){
    $model_data = $this->vehicle_model->get_model($make);
    echo json_encode($model_data);
}   

public function get_model($make){

    $this->db->select('models_id, models_name');    
    $this->db->where('makes_id', $make);
    $models_data = $this->db->get('Models');

    $rows = array();
    $rows[0] = '-Select-';
    foreach($models_data->result() as $value){
        $rows[$value->models_id] = $value->models_name;
    }
    return $rows;
}

我遇到的问题是,如果我将 0 或 1 传递给 get_model_by_make() 函数,则返回的 json 数据没有数组键。

例子:

$data = get_model_by_make(1)
echo $data; 

结果:

["-Select-","CL","CSX","EL","Integra","Legend","MDX","NSX","RDX","RL","RSX",
"SLX","TL","TSX","Vigor"]

如果传递的数字大于 1,则返回如下:

$data = get_model_by_make(2)
echo $data; 

结果:

{"0":"-Select-","35":"Alliance","36":"Ambassador","37":"AMX","38":"Classic"}

为什么json_encode不返回 0 或 1 的键/值对?如果我var_dump是数据,则键/值就在那里。

4

2 回答 2

6

You're looking at two different JSON data structures. One is an array, the other an object. Essentially, json_encode() will use the former where possible, and switch to objects if the data can't be represented by an array.

Change json_encode($model_data); to json_encode($model_data, JSON_FORCE_OBJECT); to make json_encode() always return an object, which will have the keys you want.

Further example:

$data = array(34,26,25,23,6);

echo json_encode($data); // [34,26,25,23,6]

echo json_encode($data, JSON_FORCE_OBJECT); // {"0":34,"1":26,"2":25,"3":23,"4":6}
于 2013-09-11T16:43:14.037 回答
0

您是否尝试过使用字符串而不是整数?喜欢

$rows['0'] = '-Select-';

等等。

于 2013-09-11T16:45:46.130 回答