Kyle Coots
Kyle Coots

Reputation: 2131

json encode returning only partial data

Here is what I have:

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;
}

The problem I'm having is if I pass a 0 or 1 to the get_model_by_make() function the json data that is returned without the array key.

Example:

$data = get_model_by_make(1)
echo $data; 

Result:

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

If the number passed is greater than 1 then its returned like this:

$data = get_model_by_make(2)
echo $data; 

Result:

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

Why is json_encode not returning the key/value pair for 0 or 1? If I var_dump the data the key/value is there.

Upvotes: 0

Views: 1447

Answers (2)

webduvet
webduvet

Reputation: 4292

Have you tried using strings not integers? like

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

and so on.

Upvotes: 0

George Brighton
George Brighton

Reputation: 5151

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}

Upvotes: 6

Related Questions