douhuireng4407 2017-01-12 19:21
浏览 111
已采纳

PHP JSON用逗号和括号编码

I have a php script to create a json output getting data from mysql database:

<?php
include("myconnection.php");

//Creamos y ejecutamos la consulta
$sql = "SELECT * FROM myTable where value='1003'";
$result=mysql_query($sql);

while($row = mysql_fetch_array($result)){
    $value1 = $row['value1'];
    $value2 = $row['value2'];

$data =  json_encode(
  array("value1" => $value1, 
  "value2" => $value2));

echo $data;
}

?>

I obtain a result like this:

{"value1":"847534837","value2":"Regular"}{"value1":"847534838","value2":"Regular"}

I want to obtain a result with brackets and commas like this:

[{"value1":"847534837","value2":"Regular"},{"value1":"847534838","value2":"Regular"}]

I've tried to put some echo sentences like this:

echo "[";
while($row = mysql_fetch_array($result)){
$value1 = $row['value1'];
$value2 = $row['value2'];

$data =  json_encode(
  array("value1" => $value1, 
  "value2" => $value2)).",";

echo $data;
}
echo "]";

But the result finishes with ",]" like this:

[{"value1":"847534837","value2":"Regular"},{"value1":"847534838","value2":"Regular"},]

I would like some help.

  • 写回答

2条回答 默认 最新

  • douwei1930 2017-01-12 19:25
    关注

    Let json_encode() do the work for you, don't try to roll your own encoder!!!

    To get the json string output you desire, just stick items you're currently encoding one at a time in another array and encode the who enchilada one time.

      $final_array = []; notation
      while($row = mysql_fetch_array($result)){
           $final_array[] = ["value1" => $row['value1'], 
                             "value2" => $row['value2']];
      }
    
     echo json_encode($final_array);
    

    NOTE: I'm assuming you're using PHP >= 5.4 and have the [] notation, otherwise replace [] and ["value1" => $row['value1'], "value2" => $row['value2']] with array() and array("value1" => $row['value1'], "value2" => $row['value2']) respectively.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大