0

我必须以以下格式打印 json

> { header: [ { "signinpage": "ABC" }, { "signinpage": "XYZ" }, {
> "signinpage": "PQR" }, { "signinpage": "ERT" } ] }

我使用了以下代码:

 while ($row = mysql_fetch_array($res,MYSQL_ASSOC)) 
  {
    $rows[] = $row["customer"];
  }

  if(mysql_num_rows($res)!= 0)
     {  
      if (!isset($responses[$row['$header']= array ()]))
      {
        for ($i=0;$i<count($rows);$i++)
        {
           if(isset($responses[$row['$header']])) 
           {
              $responses[$row[$header]] = array('signinpage'=>$rows[$i]); 
           }  
         }
       }
       header('Cache-Control: no-cache, must-revalidate');
       header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
       header('Content-type: application/json; charset="utf-8"');
       echo json_encode($responses);
     }

我是 JSON 新手,发现很难打印,谁能帮我获得所需的输出。提前谢谢你。

4

3 回答 3

0

$responses = array();在您的 while 循环之前添加此 linw。

$responses = array();
 while ($row = mysql_fetch_array($res,MYSQL_ASSOC)) 
  {
    $rows[] = $row["customer"];
  }

  if(mysql_num_rows($res)!= 0)
     {  
      if (!isset($responses[$row['$header']= array ()]))
      {
        for ($i=0;$i<count($rows);$i++)
        {
           if(isset($responses[$row['$header']])) 
           {
              $responses[$row[$header]] = array('signinpage'=>$rows[$i]); 
           }  
         }
       }
       header('Cache-Control: no-cache, must-revalidate');
       header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
       header('Content-type: application/json; charset="utf-8"');
       echo json_encode($responses);
     }

代码中的 $header 是什么,它没有分配任何值。

if (!isset($responses[$row['$header']= array ()]))这是错误的。键不能是数组

于 2013-03-06T08:47:55.883 回答
0

现在试试这个它应该适合你:

$rows = array();
while($row = mysql_fetch_array($res)) { 
$rows[$row['$header']][]['signinpage']=$row['customer'];
}
print json_encode($rows);

愿这对你有帮助!

于 2013-03-06T08:50:14.900 回答
0

你的循环有问题。我看不到您的 $row / $header 变量的设置位置以及其中的内容。而且你写的 isset 条件是错误的。尝试这样的事情:

$responses = array();
while ($row = mysql_fetch_array($res,MYSQL_ASSOC))  {
    $rows[] = $row["customer"];
}

if(mysql_num_rows($res)!= 0) {  
    if (!isset($responses[$row['$header']])) {
        // in case it is not set, create an array..,
        $responses[$row['$header']]= array();
        for ($i=0; $i<count($rows); $i++) {
            // for each row add your assoziative array to it
            $responses[$row[$header]][] = array('signinpage'=>$rows[$i]); 
        }
    }
}
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json; charset="utf-8"');
echo json_encode($responses);
于 2013-03-06T09:00:40.927 回答