强制 json_encode 将(稀疏)数组编码为 php 中的索引数组
我正在尝试使用 JSON 在主机和我的网页之间传输数组。在主机上,我有一个 php 脚本,它从 mysql 表中读取多行并从中创建一个数组。
$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);
通常,ID 在 0 和 99 之间线性递增。在这种情况下,json_encoded 输出是一个数组(并且将被解释为 javascript 中的数组...如果我执行 array.length,我会得到100 作为答案)....
有时,表中缺少一些行(可能没有 idx=40 的行)...在这种情况下,数组被 json_encoded 作为对象的集合。在 javascript 中,如果我尝试查看 array.length,我会得到未定义的结果。我想强制将数据数组解释为索引数组,其中缺失行的值为 null/0。有没有简单的方法可以做到这一点?看起来 json_encode 函数有一个选项可以强制编码为关联数组,但反之则不然。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我将 $data 定义为完整数组,然后替换其中的元素。
I would define $data as a full array and then replace elements inside of it.
这很烦人,但这就是适合你的 Javascript。我通常通过在数据结构中添加另一个级别来解决这个问题:
这样您就可以“免费”获得包含的长度,而无需执行任何客户端循环/计数。
It's annoying, but that's Javascript for you. I usually work around this by adding another level to my data structure:
That way you get the length included for "free", without having to do any client-side looping/counting.