我需要将这个json翻译成一个php数组,然后循环遍历这些项并将它们放入各自的列我已经尝试过使用json解码但是我回来的是文本数组我知道请求工作正常给出以下输出:
[{"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解码似乎不能只是但是这成为一个关联数组我试图使用它的方式继承人请求
$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我做错了什么时只有数组
答案 0 :(得分:2)
您的JSON数据是一个对象数组:
尝试这样做:
echo $roomdata[0]->roomType;
如果你print($roomdata)
,它将始终显示Array
,因为它就是这样。有关更多信息,请阅读json_decode:http://php.net/manual/en/function.json-decode.php
答案 1 :(得分:1)
解码JSON不会神奇地将事物放入关联数组中。您在那里的JSON结构代表一个对象数组。您需要将此映射到关联数组,如下所示:
$object_array = json_decode($rawdatar);
$result_array = array();
foreach($object_array as $obj) {
$result_array[$obj->roomType] = $obj->roomTypeCode;
}