doutang6819 2013-01-25 15:45
浏览 28
已采纳

如何从用PHP编写的Web服务输出JSONArray

I have webservice written in PHP that reads from the local database and output the result in JSON.

However, I am unable to output it into a JSONArray.

Here is the php script

<?php
$username = "root";
$password = "";
$hostname = "localhost"; 

$response=array();

//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) 
or die("Unable to connect to MySQL");

//select a database to work with
$selected = mysql_select_db("test",$dbhandle) 
or die("Could not select test");

//execute the SQL query and return records
$result = mysql_query("SELECT name, country FROM android");

$response["infos"] = array();   

while ($row = mysql_fetch_assoc($result)) {

    $info = array();
$info["name"]=$row["name"];
$info["country"]=$row["country"];

    print(json_encode($info));

}

//close the connection
mysql_close($dbhandle);
?>

This is the output from the webservice

{"name":"develop","country":"mru"}{"name":"fufu","country":"tutu"}  {"name":"chikaka","country":"aceVentura"}

But I have been told that this is not in JSONArray.

What am I missing here?

Thank you

  • 写回答

1条回答 默认 最新

  • dongyi1441 2013-01-25 15:52
    关注

    In your example you're echo'ing out multiple JSON strings because your output code is within a while loop. There should only be one output for the JSON string. The code below will give you a two dimensional array in JSON format.

    $info = array();
    
    while ($row = mysql_fetch_assoc($result)) 
    {
         $arr = array();
         $arr["name"] = $row["name"];
         $arr["country"] = $row["country"];
         $info[] = $arr;
    }
    
    echo json_encode($info);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大