如何循环Json响应

时间:2013-06-13 09:59:08

标签: php json

我有网页让Json像这样回应

{
   'hotel_1page':[
      {
         'id':'10',
         'name':'fsf',
         'telephone':'233333'
      },
      {
         'id':'11',
         'name':'setttttt',
         'telephone':'213123123'
      },
      {
         'id':'12',
         'name':'fsdfsdf',
         'telephone':'122212121'
      },
      {
         'id':'13',
         'name':'xxcvcxv',
         'telephone':'2147483647'
      },
      {
         'id':'14',
         'name':'dssdfg',
         'telephone':'2147483647'
      },
      {
         'id':'15',
         'name':'dfsdfsdf',
         'telephone':'21312321'
      },
      {
         'id':'16',
         'name':'fx_test_nw1',
         'telephone':'23232323'
      },
      {
         'id':'17',
         'name':'fx_test_nw2',
         'telephone':'31313131'
      }
   ]
}

我想循环遍历这些数据并将这些数据传输到数组并显示为html如何实现此目的

这是我得到json响应的地方,当我var_dump json编码变量时它表示null,其中$json变量显示json响应,

$json = file_get_contents('http://www.example.com/hotel_list.php'); 

var_dump($json);  
$array = json_decode($json, true);
var_dump($array);

2 个答案:

答案 0 :(得分:2)

您尝试解析的json无效。将单引号更改为双引号,您应该能够将其解析为数组。

JSON documentation

  

值可以是双引号或数字,或true或false或null,或对象或数组的字符串。这些结构可以嵌套。

答案 1 :(得分:1)

这应该有效:

$json = '{ "hotel_1page": [ { "id": "10", "name": "fsf", "telephone": "233333" }, { "id": "11", "name": "setttttt", "telephone": "213123123" }, { "id": "12", "name": "fsdfsdf", "telephone": "122212121" }, { "id": "13", "name": "xxcvcxv", "telephone": "2147483647" }, { "id": "14", "name": "dssdfg", "telephone": "2147483647" }, { "id": "15", "name": "dfsdfsdf", "telephone": "21312321" }, { "id": "16", "name": "fx_test_nw1", "telephone": "23232323" }, { "id": "17", "name": "fx_test_nw2", "telephone": "31313131" } ] }';

echo '<pre>';
var_dump(json_decode($json, true));
echo '</pre>';

我用双引号替换了所有单引号,这就是诀窍 我使用单引号导致json_decode返回null

[编辑使用]

要使用这些数据,您可以使用以下内容:

 $obj = json_decode($json, true);

 foreach($obj as $row)
 {
     foreach($row as $key => $item)
     {
         // $item['id']
         // $item['name']
         // $item['telephone']
     }
 }

我正在使用嵌套的foreach(),因为id,name和telephone是hotel_page1数组中的数组