使用php编码json吗? [英] encode json using php?

查看:84
本文介绍了使用php编码json吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用php编码功能获取json,如下所示

I want to get json with php encode function like the following

<?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是类似的

i want the output json to be something like that

{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]}

,但输出json如下所示

but the output json is look like the following

{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},]}

当您意识到结尾处有逗号时,我想将其删除,因此它可以是正确的json语法,如果在有多个结果的情况下删除了echo ",";,则json会像这样生成{"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]},并且语法也是错误的

As you realize that there is comma at the end, i want to remove it so it can be right json syntax, if i removed the echo ","; when there's more than one result the json will generate like this {"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]} and that syntax is wrong too

希望每个人都明白我的意思,任何想法都会受到赞赏

Hope that everybody got what i mean here, any ideas would be appreciated

推荐答案

如果我是你,我不会json_encode每个单独的数组,而是将这些数组合并在一起,然后在最后将json_encode合并的数组合并.以下是使用 5.4的短数组语法的示例:

If I were you, I would not json_encode each individual array, but merge the arrays together and then json_encode the merged array at the end. Below is an example using 5.4's short array syntax:

$out = [];
while(...) {
  $out[] = [ 'id' => $i, 'name' => $row['name'] ];
}
echo json_encode($out);

这篇关于使用php编码json吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆