1

ローカルデータベースから読み取り、結果をJSONで出力するPHPで記述されたWebサービスがあります。

ただし、JSONArrayに出力できません。

これがphpスクリプトです

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

これはWebサービスからの出力です

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

しかし、これはJSONArrayにはないと言われています。

ここで何が欠けていますか?

ありがとうございました

4

1 に答える 1

7

あなたの例では、出力コードがwhileループ内にあるため、複数のJSON文字列をエコーアウトしています。JSON文字列の出力は1つだけにする必要があります。以下のコードは、JSON形式の2次元配列を提供します。

$info = array();

while ($row = mysql_fetch_assoc($result)) 
{
     $arr = array();
     $arr["name"] = $row["name"];
     $arr["country"] = $row["country"];
     $info[] = $arr;
}

echo json_encode($info);
于 2013-01-25T15:52:12.980 に答える