开发者

Getting data from JSON with PHP [duplicate]

This 开发者_高级运维question already has an answer here: How to extract and access data from JSON with PHP? (1 answer) Closed 10 months ago.

Here's the 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}]

I wanted to know how I could echo out all networks so it echos out the site_url,network, and user for each of the 2.

How would I get "name" at the end out of there as well?

Tanks!


Use json_decode() http://php.net/manual/en/function.json-decode.php

  $data = json_decode(...your sstring ...);
  echo $data[0]->name;


Use json_decode to decode the JSON data. Then you can iterate the array with foreach and access the site_url‍s of each array item with another foreach like:

$arr = json_decode($json);
foreach ($arr as $obj) {
    foreach ($obj->profile->networks as $network) {
        echo $network->site_url;
    }
}


http://lt2.php.net/json_decode


Here's a straight-forward example doing the two things that you ask for (see inline comments).

$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;

It should output (if you're viewing as HTML, it will be munged onto one line… don't output as HTML).

site_url = http://site.com
network  = test
user     = mike
site_url = http://site.com/2
network  = test2
user     = mike2
name     = Mike Jones


Building on aviv's answer...

$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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜