0

我正在尝试使用 PHP 对我的 SQL SELECT 语句的结果进行 JSON 编码,并且不确定我在编码之前是否正确格式化了我的数组。

我的 PHP 代码是:

$stmt = $this->db->prepare('SELECT  CLINIC.clinic_name AS "clinicname" FROM CLINIC ORDER BY CLINIC.clinic_name ASC');

$stmt->execute();
$stmt->bind_result($clinicname);            
$test = array();                   
while($stmt->fetch()){
    $tempArray = array('clinicname' => $clinicname);
    array_push($test, $tempArray);
}
$stmt->close();

// Return clinics, encoded with JSON
header('Content-type: application/json');

$json = json_encode($test);
echo $json;

这个数组创建和编码的结果是:

[{"clinicname":"Bangor"},{"clinicname":"Belfast"},{"clinicname":"Crumlin"},{"clinicname":"Londonderry"}]

所以我有一个数组数组。

这可以作为 JSON 发送吗?我看到的所有示例似乎都是一个数组。到目前为止我是正确的吗?

然后,关于 iOS,接收到的对象是 NSDictionary 还是 NSArray?

任何关于上述内容的帮助或反馈都将受到极大的欢迎。

  • 马特。
4

3 回答 3

0

是的,您的 JSON 格式正确。下次您可以使用JSON 验证器进行检查。

另外,关于json_encoding的一些细节。

[] 代表一个数组,{} 代表一个对象。

于 2012-05-03T15:35:02.457 回答
0

在 iOS 中,如果这是来自 http 请求的结果,它将是 NSString 类型,然后需要通过以下方式解析:

http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html

然后将其转换为 NSArray、NSDictionary NSString 等。

于 2012-05-03T15:35:05.783 回答
0

是的,您可以发送数组数组,并且可以通过以下方式访问:

$response = json_decode($response,true);

  foreach ($response as $resp)
  {
    echo "<br>";
    print_r($resp);
  }  

json 示例:

[{"id":"38","first_name":"prueba","second_name":"example","first_surname":"prueba","second_surname":"GONZALEZ","email":"x@x.net","network_login":"x.x","pos_name":"x x","position":"1","active":"1"},{"vhur":"292","first_name":"c","second_name":"example","first_surname":"example","second_surname":null,"email":"example@example.com","network_login":"example.example","pos_name":"example example","position":"2","active":"1"}]
于 2012-05-03T15:39:38.367 回答