2013-10-22 75 views
1

我在PHP中解析數組時遇到了挑戰。這裏是陣列的輸出:用解碼解析PHP數組

[{"address":"2801 Elliott Ave","category_ids":[347],"category_labels":[["Social","Food and 
Dining","Restaurants"]],"country":"us","email":"[email protected]","factual_id":"43cfe23 
8-ae8e-469a-8592-a1edc8603051","fax":"(206) 448- 
9252","latitude":47.615154,"locality":"Seattle","longitude":-122.353724,"name":"The Old 
Spaghetti Factory","neighborhood":["Belltown","Downtown","Downtown 
Seattle"],"postcode":"98121","region":"WA","tel":"(206) 441- 
7724","website":"http:\/\/www.osf.com"}] 

這裏是解析嘗試...

$mark = array("["); 
$mark2 = array("]"); 
$replacemark = array(""); 
$array = str_replace($mark, $replacemark, $array); 
$array = str_replace($mark2, $replacemark, $array); 
$array = stripslashes($array); 

$obj = json_decode($array); 

$address = $obj->{'address'}; 
$country = $obj->{'country'}; 
$factual_id = $obj->{'factual_id'}; 
$latitude = $obj->{'latitude'}; 
$locality = $obj->{'locality'}; 
$longitude = $obj->{'longitude'}; 
$name = $obj->{'name'}; 
$postcode = $obj->{'postcode'}; 
$region = $obj->{'region'}; 
$status = $obj->{'status'}; 
$tel = $obj->{'tel'}; 

任何想法,爲什麼這些值不返回任何東西?謝謝!

+1

什麼是所有替代atop應該完成? – mario

回答

1

沒有必要去掉方括號。只需撥打電話json_decode()即可獲取您的信息。

注:在表單中的數據,你有它解碼爲對象的數組,只有一個對象,所以你需要提供一個數組下標:

$json = json_decode("My JSON Data...here"); 
echo $json[0]->address; 

this fiddle

2nd注意:由於您發佈的數據中包含換行符,導致json_decode()出現問題。如果您的原始數據中包含這些數據,則需要在解碼之前將其去除。我在小提琴中編輯它們。

0

你並不需要刪除JSON字符串方括號,然後嘗試訪問像你的價值觀$obj->address

編輯:

這JSON字符串索引0與你的對象返回一個數組,測試自己,所以要訪問您的值,您將需要:$obj[0]->address或設置您的對象$obj = $de_json[0];並訪問如上所述的值

+0

'json_decode()'返回有NULL和無括號的NULL' – Darren

+0

對我來說工作正常,唯一的問題是解碼時的JSON字符串返回包含索引爲0的對象的數組,因此需要進行一些調整 – GroovyCarrot