0

我需要将此 json 转换为 php 数组,然后循环遍历这些项目并将它们放入相应的列中输出 :

 [{"roomType":"Single rooms","roomTypeCode":"SB"},{"roomType":"Double rooms","roomTypeCode":"DB"},{"roomType":"Twin rooms","roomTypeCode":"TB"},{"roomType":"Triple rooms","roomTypeCode":"TR"},{"roomType":"Suites","roomTypeCode":"S"},{"roomType":"Non-smoking rooms","roomTypeCode":"NS"},{"roomType":"Quad rooms","roomTypeCode":"Q"},{"roomType":"Twin for sole use","roomTypeCode":"TS"}]

如果我将需要解码的字符串全部打印出来,但 json decode 似乎无法将其转换为关联数组,就像我尝试使用它的方式一样,这就是请求

$ch = curl_init();
$timeout = 0;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdatar = curl_exec($ch);
curl_close($ch);
$roomdata = json_decode($rawdatar);
print $roomdata;

如果我打印 $rawdatar 我得到前面提到的 json 行,但当我打印 $roomdata 时除了数组什么都没有我做错了什么

4

2 回答 2

2

您的 JSON 数据是一组对象:

尝试这样做:

echo $roomdata[0]->roomType;

如果你print($roomdata),它会一直显示Array,因为它就是这样。有关更多信息,请阅读 json_decode:http ://php.net/manual/en/function.json-decode.php

于 2012-08-10T18:43:33.300 回答
1

解码 JSON 不会神奇地将事物放入关联数组中。您那里的 JSON 结构代表一个对象数组。您需要自己将其映射到关联数组,如下所示:

$object_array = json_decode($rawdatar);
$result_array = array();
foreach($object_array as $obj) {
    $result_array[$obj->roomType] = $obj->roomTypeCode;
}
于 2012-08-10T18:43:51.610 回答