json_encode mysql_fetch_array 重复,PHP json_encode两次对相同数据进行编码

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 .= ',';

}

}

}

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

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)

Many thanks

解决方案

This is because you are using fetch_array() (emphasis mine):

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.

Use fetch_assoc() instead.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值