我想用如下的php编码功能获取json
<?php require "../classes/database.php"; $database = new database(); header("content-type: application/json"); $result = $database->get_by_name($_POST['q']); //$_POST['searchValue'] echo '{"results":['; if($result) { $i = 1; while($row = mysql_fetch_array($result)) { if(count($row) > 1) { echo json_encode(array('id'=>$i, 'name' => $row['name'])); echo ","; } else { echo json_encode(array('id'=>$i, 'name' => $row['name'])); } $i++; } } else { $value = "FALSE"; echo json_encode(array('id'=>1, 'name' => "")); // output the json code } echo "]}";
我希望输出json是这样的
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]}
但输出json如下所示
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},]}
当您意识到结尾处有逗号时,我想将其删除,以便使用正确的json语法。如果删除了echo ",";多个结果时json会像这样生成{"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]},并且语法也是错误的,则删除json语法
echo ",";
{"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]}
希望每个人都明白我的意思,任何想法都将不胜感激
如果我是你,我不会json_encode每个单独的数组,而是将数组合并在一起,然后json_encode在最后合并数组。下面是使用5.4的短数组语法的示例:
json_encode
$out = []; while(...) { $out[] = [ 'id' => $i, 'name' => $row['name'] ]; } echo json_encode($out);