php json_encode两次对相同数据进行编码 [英] php json_encode is encoding the same data twice
问题描述
我正在从数据库中获取一些数据,并将其编码为json:
I am getting some data from a database and am encoding it to json:
$json = "";
if($result = $dbc->query($query)) {
$num = $result->num_rows;
for($i = 0; $i < $num; $i++) {
$row = $result->fetch_array();
$json .= json_encode($row);
if($i != ($num-1)) {
$json .= ',';
}
}
}
,而不是获取以下格式的json字符串:
but instead of getting the json string in the format:
{"name:"joe", "age":"22", "etc":"etc"}
我得到的每个值都是重复的,因为它为元素名称提供了既是关联数组又是非关联数组的索引.所以我得到了:
I'm getting every value duplicated because it is giving me the element name as being both the index of an associative and non-associative array. So I'm getting:
{"0":"joe", "name":"joe", "1":"22", "age":"22", "3":"etc", "etc":"etc"}
虽然我仍然可以使用json.它仍然是我想要的大小的两倍,因此效率不高.无论如何,我可以得到json_encode方法来给我关联数组inice作为json标签吗? (毫无疑问,用错误的词形容这些事情)
While I can still use the json. It is still twice the size that I want it to be and so not efficient. Is there anyway I can get the json_encode method to just give me the associative array inices as the json tags? (Wrong words to describe these things no doubt)
非常感谢
推荐答案
这是因为您正在使用 fetch_array()
(强调我的意思):
This is because you are using fetch_array()
(emphasis mine):
mysqli_fetch_array()是mysqli_fetch_row()函数的扩展版本. 除了将数据存储在结果数组的数字索引中,mysqli_fetch_array()函数还可以将结果集的字段名称用作键,将数据存储在关联索引中.
mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.
改为使用fetch_assoc()
.
这篇关于php json_encode两次对相同数据进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!