I am trying to transfer an array between the host and my webpage using JSON. On the host, I have a php script which reads a number of rows from a mysql table and creates an array out of it.
$query="select ID,val,size from db;";
$result=mysql_query($query);
while ($row=mysql_fetch_assoc($result)) {
$idx= (int) $row['ID'];
$data[$idx]['val']=$row['val'];
$data[$idx]['size']=$row['size'];
}
echo json_encode($data);
Normally, the ID's are incremented linearly between, for example, 0 and 99.. In this case, the json_encoded output is an array (and will be interpreted as an array in javascript... If I do an array.length, I get 100 as the answer)....
Sometimes, a few of the rows are missing from the table (maybe there was no row with an idx=40)... In this case, the array is json_encoded as a collection of objects. In javascript, if I try to look at array.length, I get an undefined result. I'd like to force the data array to be interpreted as an indexed array with null/0 values for missing rows. Is there an easy way to do this? It looks like the json_encode function has an option to force encoding as an associative array, but not the other way around.
Thx.
$data['length']=count($data)
? If you need the length for looping over the data, gaps in the numbers will mess it up/report incorrect length values. You can use afor in
loop (similar to a php foreach).