2014-02-14 65 views
0

我試圖在PHP中以數組的形式獲取JSON文件中的信息,所以我可以將它放入我的數據庫中。在這個簡單的例子我的代碼工作:在PHP中獲取JSON信息

{ 
"tiles":[179, 199, 198, 198, 160, 198, 180, 199, 178, 160, 180, 180, 198, 160] 
} 

$string = file_get_contents(FileDestination); 
$worldarray = json_decode($string, true); 
foreach($worldarray['tiles'] as $item) { 
    mysqli_query($link, 'INSERT INTO blabla (test) VALUES('.$item.')'); 
} 

然而,恰巧我的JSON文件是一個比較複雜:

{ "height":32, 
"layers":[ 
    { 
    "data":[179, 199, 198, 198, 160, 198, 180, 199, 178, 160, 180, 180, 198, 160, 178,], 
    "height":32, 
    "name":"Tile Layer 1", 
    "opacity":1, 
    "type":"tilelayer", 
    "visible":true, 
    "width":32, 
    "x":0, 
    "y":0 
    }, 

等。我需要圖層>數據中的信息。我嘗試過以各種方式訪問​​它:$ worldarray ['layers'] ['data']但我似乎無法從數據中獲取值。誰能幫我這個?提前致謝。

+0

它只看起來更復雜,但事實並非如此。只是嵌套。 'foreach($ worldarray ['layers'] [0] ['data'] as $ item)' – DanFromGermany

+0

首先; 'print_r(json_decode($ string,true))的輸出是什麼? (ot:nice nick,jan lul;)) – giorgio

+0

請顯示json數據,因爲它在文件中... – Lab

回答

1

作爲layers是一個陣列中,當訪問你應該提供一個索引,如:

$worldarray['layers'][0]['data'] 

如果你有當然更多層,則應該在它們之間迭代。

+0

當我這樣做時,沒有任何內容添加到我的數據庫中。這是唯一的圖層和唯一的數據。 –

1
$json = file_get_contents('url_here'); 
    $obj = json_decode($json); 
    echo $obj->access_token; 

嘗試這種方式。我希望這是可能的幫助大家的幫助

0

謝謝,突然現在的工作,通過使用$陣列['層'] [0] [' 數據']。儘管之前沒有多少工作。