使用Decode解析PHP数组

时间:2013-10-22 01:24:26

标签: php arrays parsing

我正在挑战在PHP中正确解析数组。这是数组的输出:

[{"address":"2801 Elliott Ave","category_ids":[347],"category_labels":[["Social","Food and 
Dining","Restaurants"]],"country":"us","email":"kimd@thedussingroup.com","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'};

为什么这些价值观没有回归任何想法?谢谢!

2 个答案:

答案 0 :(得分:1)

无需剥开方括号。只需在数据上调用json_decode()并检索您的信息即可。

注意:您将表单中的数据解码为一个对象数组,只有一个对象,因此您需要提供一个数组下标:

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

请参阅this fiddle

第二个注意:您发布的数据已嵌入新行,导致json_decode()出现问题。如果原始数据中包含这些数据,则需要在解码前将其剥离。我把它们编成了小提琴。

答案 1 :(得分:0)

您无需删除JSON字符串中的方括号,然后尝试访问$obj->address

等值

编辑:

JSON字符串返回一个数组,其对象位于索引0处,我自己进行了测试,因此要访问您的值,您需要:$obj[0]->address或设置对象$obj = $de_json[0];并访问上面所述的值