json_decode
给你一个关联数组您传递“true”作为第二个参数 http://www.php.net/manual/en/function.json-decode.php:
$json = '[{"Id":1079,"Name":"Test ","Status":1,"MemberId":1308,"Description":"This is a Test Event","SponsoredBy":null,"StartTime":"2013-06-30T12:00:00","EndTime":"2013-06-30T23:59:00","SearchDescription":null,"Types":[1,4,6]}]';
$response = json_decode($json, true);
echo $response[0]["Name"];
gives:
Test
Edit:
json_decode()
返回一个数组数组,因此您需要引用位于位置的数组[0]
在回复中,如果你明白我的话。
我在上面的示例中使用 $response[0] 完成了这一点,但是看看这个示例,希望它能让它更清楚!
$result = json_decode($json, true);
var_dump($result);
gives:
array(1) {
[0]=>
array(10) {
["Id"]=>
int(1079)
["Name"]=>
string(5) "Test "
["Status"]=>
int(1)
["MemberId"]=>
int(1308)
["Description"]=>
string(20) "This is a Test Event"
["SponsoredBy"]=>
NULL
["StartTime"]=>
string(19) "2013-06-30T12:00:00"
["EndTime"]=>
string(19) "2013-06-30T23:59:00"
["SearchDescription"]=>
NULL
["Types"]=>
array(3) {
[0]=>
int(1)
[1]=>
int(4)
[2]=>
int(6)
}
}
}
然后..访问数组本身:
$result = json_decode($json, true);
$result = $result[0]; // let's just reassign this to get the array we want
var_dump($result);
gives:
array(10) {
["Id"]=>
int(1079)
["Name"]=>
string(5) "Test "
["Status"]=>
int(1)
["MemberId"]=>
int(1308)
["Description"]=>
string(20) "This is a Test Event"
["SponsoredBy"]=>
NULL
["StartTime"]=>
string(19) "2013-06-30T12:00:00"
["EndTime"]=>
string(19) "2013-06-30T23:59:00"
["SearchDescription"]=>
NULL
["Types"]=>
array(3) {
[0]=>
int(1)
[1]=>
int(4)
[2]=>
int(6)
}
}
现在您可以直接访问数组的各个元素:
$result = json_decode($json, true);
$result = $result[0];
echo "Name: ". $result["Name"] . "\nID: " . $result["Id"] . "\nDescription: " . $result["Description"] . "\n";
现在我们回来了:
Name: Test
ID: 1079
Description: This is a Test Event
希望这是有道理的!