php转为json格式,如何将PHP数据转换为json格式?

在这里我正在使用php代码获取数据.但是我想将相同的代码转换为json格式.我没有办法做到这一点.

我已经尝试过这种方式.

我的代码

while ($rows = mysql_fetch_array($filter)) {

$result['name'] = $rows['name'];

$result['id'] = $rows['id'];

}

$res = json_encode($result);

print_r($res);

得到结果

{"name":["sradha","nicky","demo","testing"],"id":["1","2","3","4"]}

在这里我想要下面的json格式

[{id:1, name:'sradha'},

{id:2, name:'nicky'},

{id:3, name:'demo'},

{id:3, name:'testing'}];

请给我建议.

任何建议将不胜感激.

先感谢您.

解决方法:

请尝试以下方法:

while ($rows = mysql_fetch_assoc($filter)) {

$result['name'] = $rows['name'];

$result['id'] = $rows['id'];

$new_result[] = $result;

}

$res = json_encode($new_result);

print_r($res);

要么

while ($rows = mysql_fetch_assoc($filter)) {

$result[] = $rows;

}

$res = json_encode($result);

print_r($res);

标签:json,php

来源: https://codeday.me/bug/20191027/1943468.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值