如何将PHP数据转换为JSON格式?

3

在这里,我正在使用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'}];

请给我提建议。 非常感谢您的任何建议。 提前致谢。


1
请不要使用 mysql_*。它已被弃用并从PHP 7中移除。请使用 mysqli_*PDO - Mr. Engineer
好的.. @工程师 工程师 - sradha
3个回答

2

试试这个

$result = array();

while ($rows = mysql_fetch_assoc($filter)) {
    $result[] = $rows;
}

echo json_encode($result);

不需要这行代码:$result = array(); - Mr. Engineer
没有必要,但最好在使用之前定义它,因为涉及到作用域。 - Haridarshan
但我只想要姓名和ID。 - sradha
整个数据都已经到齐了,有什么建议吗? - sradha
好的,但是我该如何从id和name中删除双引号呢? 我的意思是它看起来像这样: [{"id":"1","name":"sradha"},{"id":"2","name":"aruna"},{"id":"3","name":"demo"},{"id":"4","name":"testing"}] - sradha
显示剩余3条评论

2

请尝试以下操作:

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);

@sradha 那第二个呢?第一个显示什么? - Kausha Mehta
如果我在做第二个时,会显示重复记录。 如果我使用mysql_fetch_assoc而不是mysql_fetch_array,它就可以工作了。否则结果会像这样:[{"name":"sradha"},{"id":"1"},{"name":"aruna"},{"id":"2"},{"name":"demo"},{"id":"3"},{"name":"testing"},{"id":"4"}] - sradha
不要使用print_r,只需使用echo $res。 - Neeraj Kumar
[{"0":"1","id":"1","1":"sradha","name":"sradha"},{"0":"2","id":"2","1":"aruna","name":"aruna"},{"0":"3","id":"3","1":"demo","name":"demo"},{"0":"4","id":"4","1":"testing","name":"testing"}] - sradha
这意味着它正在工作,但问题在于使用mysql_fetch_array而不是mysql_fetch_assoc... 我只关注你的查询,它与获取数据而不是重复有关... - Kausha Mehta
显示剩余3条评论

0

按照以下方式创建您的数组

$i=0;
while($rows = mysql_fetch_array($filter)) {
    $result[$i]['name'] = $rows['name'];
    $result[$i]['id'] = $rows['id'];
    $i++;
}
$res = json_encode($result);
print_r($res);

它将返回输出结果


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接