这是json
[{"location":"USA","email":"test@test.com","sex":"male","age":"Unkown","other":null,"profile":{"net":["55","56"],"networks":[{"site_url":"http://site.com","network":"test","username":"mike"},{"site_url":"http://site.com/2","network":"test2","username":"mike2"}]},"name":"Mike Jones","id":111}]
我想知道如何能够回应所有网络,以便它为2中的每一个回应site_url,网络和用户。
我怎么会在那里得到“名字”呢?
坦克!
答案 0 :(得分:5)
使用json_decode() http://php.net/manual/en/function.json-decode.php
$data = json_decode(...your sstring ...);
echo $data[0]->name;
答案 1 :(得分:3)
使用json_decode
解码JSON数据。然后,您可以使用foreach
迭代数组,并使用另一个foreach
访问每个数组项的 site_url :
$arr = json_decode($json);
foreach ($arr as $obj) {
foreach ($obj->profile->networks as $network) {
echo $network->site_url;
}
}
答案 2 :(得分:0)
答案 3 :(得分:0)
以aviv的答案为基础......
$data = json_decode(...your sstring ...);
echo $data[0]->location; // USA
...
echo $data[0]->profile->net[0]; // 55
echo $data[0]->profile->net[1]; // 56
echo $data[0]->profile->networks[0]->site_url; // http://site.com
echo $data[0]->profile->networks[0]->network; // test
echo $data[0]->profile->networks[0]->username; // mike
echo $data[0]->profile->networks[1]->site_url; // http://site.com/2
echo $data[0]->profile->networks[1]->network; // test2
echo $data[0]->profile->networks[1]->username; // mike2
echo $data[0]->name; // Mike Jones
答案 4 :(得分:0)
这是一个直截了当的例子来做你要求的两件事(参见内联评论)。
$json = '[{"location":"USA","email":"test@test.com","sex":"male","age":"Unkown","other":null,"profile":{"net":["55","56"],"networks":[{"site_url":"http://site.com","network":"test","username":"mike"},{"site_url":"http://site.com/2","network":"test2","username":"mike2"}]},"name":"Mike Jones","id":111}]';
// "Decode" JSON into (dumb) native PHP object
$data = json_decode($json);
// Get the first item in the array (there is only one)
$item = $data[0];
// Loop over the profile.networks array
foreach ($item->profile->networks as $network) {
// echos out the site_url,network, and user
echo "site_url = " . $network->site_url . PHP_EOL;
echo "network = " . $network->network . PHP_EOL;
echo "user = " . $network->username . PHP_EOL;
}
// Get "name" at the end
echo "name = " . $item->name . PHP_EOL;
它应该输出(如果您以HTML格式查看,它将被导入一行......不输出为HTML)。
site_url = http://site.com
network = test
user = mike
site_url = http://site.com/2
network = test2
user = mike2
name = Mike Jones