0

我得到这样的 json 格式

[{"service":{"title":"karthik","city":"chennai"}},{"service":{"title":"siva","city":"madurai"}}]

从代码

$rt = array();
$rt["service"]["title"] = karthik;
$rt["service"]["city"] = chennai;

$t = array();
$t["service"]["title"] = siva;
$t["service"]["city"] = madurai;

echo json_encode(array($rt,$t));

但我需要此代码的相同格式的 json 结果

$a=mysql_query("SELECT  title,city,category,parentid,pay,task.id 
FROM task");
while($row=mysql_fetch_array($a))
{
$jsonrow=new stdClass;
$jsonrow->title=$row['title'];
$jsonrow->city=$row['city'];


$jsonresponse=new stdClass;
$jsonresponse->service=$jsonrow;

}

echo json_encode(array($jsonresponse));

但实际上我从上面的代码得到的结果是

[{"service":{"title":"Event Help","city":"Santa Fe"}}]

请有人帮我解决这个问题......

4

3 回答 3

3

使用数组存储查询返回的所有值

$array = array();
$a=mysql_query("SELECT  title,city,category,parentid,pay,task.id 
FROM task");
while($row=mysql_fetch_array($a))
{
  $jsonrow=new stdClass;
  $jsonrow->title=$row['title'];
  $jsonrow->city=$row['city'];


  $jsonresponse=new stdClass;
  $jsonresponse->service=$jsonrow;
  $array[] = $jsonresponse;
}

echo json_encode(array($array));
于 2012-12-15T08:33:25.280 回答
1

你正在覆盖$jsonresponse你的while循环,你应该把它添加到数组和json_encode这个数组中

$response = array();

while( ... ){
    ...
    $response[] = $jsonresponse;
}
echo json_encode($response);
于 2012-12-15T08:33:07.573 回答
0

试试这样

  $a=mysql_query("SELECT  title,city,category,parentid,pay,task.id  FROM
  task");

  $jsonrow=new stdClass;
  $jsonresponse=new stdClass;
  while($row=mysql_fetch_array($a)) {

  $jsonrow->title=$row['title']; $jsonrow->city=$row['city'];    
  $jsonresponse->service=$jsonrow;

   }
于 2012-12-15T08:31:19.597 回答