需要从php获取json格式

时间:2012-12-15 08:26:44

标签: php json

我正在获得像这样的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"}}]

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

3 个答案:

答案 0 :(得分: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));

答案 1 :(得分:1)

你在while循环中覆盖$jsonresponse,你应该将它添加到数组中并json_encode这个数组

$response = array();

while( ... ){
    ...
    $response[] = $jsonresponse;
}
echo json_encode($response);

答案 2 :(得分: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;

   }