I am retrieving artist information from the last.fm API. Here is a sample response for U2:
{
"artist" : {
"stats" : {
"playcount" : "117896887",
"listeners" : "3077194"
},
"name" : "U2",
"tags" : {
"tag" : [
{
"url" : "http://www.last.fm/tag/rock",
"name" : "rock"
},
{
"url" : "http://www.last.fm/tag/classic%20rock",
"name" : "classic rock"
},
{
"url" : "http://www.last.fm/tag/irish",
"name" : "irish"
},
{
"url" : "http://www.last.fm/tag/pop",
"name" : "pop"
},
{
"url" : "http://www.last.fm/tag/alternative",
"name" : "alternative"
}
]
},
"image" : [
{
"#text" : "http://userserve-ak.last.fm/serve/34/12369741.jpg",
"size" : "small"
},
{
"#text" : "http://userserve-ak.last.fm/serve/64/12369741.jpg",
"size" : "medium"
},
{
"#text" : "http://userserve-ak.last.fm/serve/126/12369741.jpg",
"size" : "large"
},
{
"#text" : "http://userserve-ak.last.fm/serve/252/12369741.jpg",
"size" : "extralarge"
},
{
"#text" : "http://userserve-ak.last.fm/serve/_/12369741/U2.jpg",
"size" : "mega"
}
],
"mbid" : "704acdbb-1415-4782-b0b6-0596b8c55e46",
"similar" : {
"artist" : [
{
"url" : "http://www.last.fm/music/Passengers",
"name" : "Passengers",
"image" : [
{
"#text" : "http://userserve-ak.last.fm/serve/34/4826014.jpg",
"size" : "small"
},
{
"#text" : "http://userserve-ak.last.fm/serve/64/4826014.jpg",
"size" : "medium"
},
{
"#text" : "http://userserve-ak.last.fm/serve/126/4826014.jpg",
"size" : "large"
},
{
"#text" : "http://userserve-ak.last.fm/serve/252/4826014.jpg",
"size" : "extralarge"
},
{
"#text" : "http://userserve-ak.last.fm/serve/500/4826014/Passengers+Brian+Eno++U2+as++Du.jpg",
"size" : "mega"
}
]
},
{
"url" : "http://www.last.fm/music/Bono",
"name" : "Bono",
"image" : [
{
"#text" : "http://userserve-ak.last.fm/serve/34/2511353.jpg",
"size" : "small"
},
{
"#text" : "http://userserve-ak.last.fm/serve/64/2511353.jpg",
"size" : "medium"
},
{
"#text" : "http://userserve-ak.last.fm/serve/126/2511353.jpg",
"size" : "large"
},
{
"#text" : "http://userserve-ak.last.fm/serve/252/2511353.jpg",
"size" : "extralarge"
},
{
"#text" : "http://userserve-ak.last.fm/serve/_/2511353/Bono.jpg",
"size" : "mega"
}
]
},
{
"url" : "http://www.last.fm/music/R.E.M.",
"name" : "R.E.M.",
"image" : [
{
"#text" : "http://userserve-ak.last.fm/serve/34/33444847.jpg",
"size" : "small"
},
{
"#text" : "http://userserve-ak.last.fm/serve/64/33444847.jpg",
"size" : "medium"
},
{
"#text" : "http://userserve-ak.last.fm/serve/126/33444847.jpg",
"size" : "large"
},
{
"#text" : "http://userserve-ak.last.fm/serve/252/33444847.jpg",
"size" : "extralarge"
},
{
"#text" : "http://userserve-ak.last.fm/serve/500/33444847/REM+11.jpg",
"size" : "mega"
}
]
},
{
"url" : "http://www.last.fm/music/Coldplay",
"name" : "Coldplay",
"image" : [
{
"#text" : "http://userserve-ak.last.fm/serve/34/28914.jpg",
"size" : "small"
},
{
"#text" : "http://userserve-ak.last.fm/serve/64/28914.jpg",
"size" : "medium"
},
{
"#text" : "http://userserve-ak.last.fm/serve/126/28914.jpg",
"size" : "large"
},
{
"#text" : "http://userserve-ak.last.fm/serve/252/28914.jpg",
"size" : "extralarge"
},
{
"#text" : "http://userserve-ak.last.fm/serve/_/28914/Coldplay.jpg",
"size" : "mega"
}
]
},
{
"url" : "http://www.last.fm/music/Bruce+Springsteen",
"name" : "Bruce Springsteen",
"image" : [
{
"#text" : "http://userserve-ak.last.fm/serve/34/2326566.jpg",
"size" : "small"
},
{
"#text" : "http://userserve-ak.last.fm/serve/64/2326566.jpg",
"size" : "medium"
},
{
"#text" : "http://userserve-ak.last.fm/serve/126/2326566.jpg",
"size" : "large"
},
{
"#text" : "http://userserve-ak.last.fm/serve/252/2326566.jpg",
"size" : "extralarge"
},
{
"#text" : "http://userserve-ak.last.fm/serve/_/2326566/Bruce+Springsteen+bruce.jpg",
"size" : "mega"
}
]
}
]
},
"streamable" : "1",
"bandmembers" : {
"member" : [
{
"yearfrom" : "1976",
"name" : "Bono"
},
{
"yearfrom" : "1976",
"name" : "The Edge"
},
{
"yearfrom" : "1976",
"name" : "Adam Clayton"
},
{
"yearfrom" : "1976",
"name" : "Larry Mullen, Jr."
},
{
"yearfrom" : "1976",
"name" : "Dick Evans"
},
{
"yearfrom" : "1976",
"name" : "Ivan McCormick"
},
{
"yearfrom" : "1976",
"name" : "Peter Martin"
}
]
},
"url" : "http://www.last.fm/music/U2",
"ontour" : "0",
"bio" : {
"published" : "Tue, 27 Sep 2011 15:29:59 +0000",
"yearformed" : "1976",
"summary" : "\n U2 is an Irish rock band which formed in 1976 in Dublin, Ireland. Since the band’s formation, they have consisted of Bono</a> (real name Paul Hewson) (vocals, guitar, harmonica), The Edge</a> (real name David Evans) (guitar, keyboards, backing vocals), Adam Clayton</a> (bass) and Larry Mullen, Jr.</a> (drums, percussion). The band is the biggest selling alternative rock act of all time, having sold 140 million albums worldwide as of 2008. They have won 22 Grammys and were inducted into the Rock & Roll Hall of Fame in 2005. As of 2009, they have released 12 albums and 58 singles. \n\n Read more about U2 on Last.fm</a>.\n \n ",
"placeformed" : "Dublin, Ireland",
"formationlist" : {
"formation" : {
"yearfrom" : "1976",
"yearto" : ""
}
},
"content" : "\n U2 is an Irish rock band which formed in 1976 in Dublin, Ireland. Since the band’s formation, they have consisted of Bono</a> (real name Paul Hewson) (vocals, guitar, harmonica), The Edge</a> (real name David Evans) (guitar, keyboards, backing vocals), Adam Clayton</a> (bass) and Larry Mullen, Jr.</a> (drums, percussion). The band is the biggest selling alternative rock act of all time, having sold 140 million albums worldwide as of 2008. They have won 22 Grammys and were inducted into the Rock & Roll Hall of Fame in 2005. As of 2009, they have released 12 albums and 58 singles. \n\n Read more about U2 on Last.fm</a>.\n \n \nUser-contributed text is available under the Creative Commons By-SA License and may also be available under the GNU FDL.\n ",
"links" : {
"link" : {
"rel" : "original",
"href" : "http://www.last.fm/music/U2/+wiki",
"#text" : ""
}
}
}
}
}
I want to display the summary only but I'm having trouble selecting it in my script. I've tried the following
echo $result->artist->bio->summary;
or
$output = $result->artist->bio->summary;
echo '<ul>';
foreach ($bands as $artist) {
$name ->name;
etc
}
if ($result === NULL) die('Artist not found');
If somebody could show me how to select and display one object from the returned JSON that would be great. I've tried everything I can think of or find
enter code hereobject(stdClass)[1]
public 'artist' =>
object(stdClass)[2]
public 'name' => string 'Foo Fighters' (length=12)
public 'mbid' => string '67f66c07-6e61-4026-ade5-7e782fad3a5d' (length=36)
public 'bandmembers' =>
object(stdClass)[3]
public 'member' =>
array (size=7)
...
public 'url' => string 'http://www.last.fm/music/Foo+Fighters' (length=37)
public 'image' =>
array (size=5)
0 =>
object(stdClass)[11]
...
1 =>
object(stdClass)[12]
...
2 =>
object(stdClass)[13]
...
3 =>
object(stdClass)[14]
...
4 =>
object(stdClass)[15]
...
public 'streamable' => string '1' (length=1)
public 'ontour' => string '0' (length=1)
public 'stats' =>
object(stdClass)[16]
public 'listeners' => string '3589242' (length=7)
public 'playcount' => string '155892081' (length=9)
public 'similar' =>
object(stdClass)[17]
public 'artist' =>
array (size=5)
...
public 'tags' =>
object(stdClass)[48]
public 'tag' =>
array (size=5)
...
public 'bio' =>
object(stdClass)[54]
public 'links' =>
object(stdClass)[55]
...
public 'published' => string 'Fri, 9 Nov 2012 21:02:30 +0000' (length=30)
public 'summary' => string '
Foo Fighters are an American rock band formed by singer/guitarist/drummer Dave Grohl in 1995 in Seattle, USA. Grohl formed the group as a one-man project after the dissolution of his previous band Nirvana in 1994. Prior to the '... (length=1384)
public 'content' => string '
Foo Fighters are an American rock band formed by singer/guitarist/drummer Dave Grohl in 1995 in Seattle, USA. Grohl formed the group as a one-man project after the dissolution of his previous band Nirvana in 1994. Prior to '... (length=1514)
public 'placeformed' => string 'Seattle, USA' (length=12)
public 'yearformed' => string '1995' (length=4)
public 'formationlist' =>
object(stdClass)[57]
...
Here is how you would parse json data:
PHP
$decodedJson = json_decode($json);
$artist = $decodedJson->{"artist"};
$bio = $artist->{"bio"};
$summary = $bio->{"summary"};
var_dump($summary);
Program Output
string(631) " U2 is an Irish rock band which formed in 1976 in
Dublin, Ireland. Since the band’s formation, they have consisted of
Bono (real name Paul Hewson) (vocals, guitar, harmonica), The
Edge (real name David Evans) (guitar, keyboards, backing vocals),
Adam Clayton (bass) and Larry Mullen, Jr. (drums, percussion).
The band is the biggest selling alternative rock act of all time,
having sold 140 million albums worldwide as of 2008. They have won 22
Grammys and were inducted into the Rock & Roll Hall of Fame in 2005.
As of 2009, they have released 12 albums and 58 singles.
Read more about U2 on Last.fm. "
Demo
Related
We have a big database. We collect newsletters and I want to make a trending page. The goal is to make the page realtime and fast! We want to display trending newsletters from the past 2 hours, 4 hours, 24 hours, past week, and past month.
I've worked with MongoDB for a while and I try to keep things simple. I want a new collection, trending, that stores the visitors of the newsletter pages in a time bucket. On every visit, I want to add the information of the newsletter to the object that holds the trending newsletters for that time and $inc the hits field for statistics.
My objects are:
{
"_id" : ObjectId("5d4b4ca5a6bba5f7ffb23b39"),
"bucket" : "last2hours",
"language" : "nl",
"time" : "2019-08-08_00",
"newsletters" : {
"5d4b29ba8ddf870fe15628c7" : {
"_id" : ObjectId("5d4b29ba8ddf870fe15628c7"),
"_slug" : "nieuwsbrief-dalstra-reizen-touring-december-2015",
"subject" : "Nieuwsbrief Dalstra Reizen Touring december 2015",
"date" : ISODate("2015-12-04T13:15:03.000+0000"),
"publisher" : {
"_id" : ObjectId("557ebcc54c79597761fd71c2"),
"_slug" : "dalstra-nl",
"name" : "dalstra.nl",
"taal" : "nl"
},
"hits" : NumberInt(1)
},
"5d4b29af8ddf870fe15624ba" : {
"_id" : ObjectId("5d4b29af8ddf870fe15624ba"),
"_slug" : "the-carolina-weddings-show",
"subject" : "The Carolina Weddings Show",
"date" : ISODate("2015-12-04T13:13:54.000+0000"),
"publisher" : {
"_id" : ObjectId("503b950fffa67e2c790007d7"),
"_slug" : "livingsocialcom",
"name" : "Livingsocial.com",
"taal" : "nl"
},
"hits" : NumberInt(1)
},
"5d4b29ad8ddf870fe15623f4" : {
"_id" : ObjectId("5d4b29ad8ddf870fe15623f4"),
"_slug" : "newport-gangster-tour",
"subject" : "Newport Gangster Tour",
"date" : ISODate("2015-12-04T13:13:22.000+0000"),
"publisher" : {
"_id" : ObjectId("503b950fffa67e2c790007d7"),
"_slug" : "livingsocialcom",
"name" : "Livingsocial.com",
"taal" : "nl"
},
"hits" : NumberInt(1)
},
"5d4b29bb8ddf870fe15628f3" : {
"_id" : ObjectId("5d4b29bb8ddf870fe15628f3"),
"_slug" : "springwise-daily-shoe-insoles-control-devices-through-kicking-and-more",
"subject" : "Springwise Daily | Shoe insoles control devices through kicking, and more.",
"date" : ISODate("2015-12-04T13:15:05.000+0000"),
"publisher" : {
"_id" : ObjectId("5581f0b54c7959e82bfd71c2"),
"_slug" : "springwise-com",
"name" : "springwise.com",
"taal" : "nl"
},
"hits" : NumberInt(2)
}
}
}
{
"_id" : ObjectId("5d4b4ca5a6bba5f7ffb23b3b"),
"bucket" : "last2hours",
"language" : "nl",
"time" : "2019-08-08_01",
"newsletters" : {
"5d4b29ba8ddf870fe15628c7" : {
"_id" : ObjectId("5d4b29ba8ddf870fe15628c7"),
"_slug" : "nieuwsbrief-dalstra-reizen-touring-december-2015",
"subject" : "Nieuwsbrief Dalstra Reizen Touring december 2015",
"date" : ISODate("2015-12-04T13:15:03.000+0000"),
"publisher" : {
"_id" : ObjectId("557ebcc54c79597761fd71c2"),
"_slug" : "dalstra-nl",
"name" : "dalstra.nl",
"taal" : "nl"
},
"hits" : NumberInt(1)
},
"5d4b29af8ddf870fe15624ba" : {
"_id" : ObjectId("5d4b29af8ddf870fe15624ba"),
"_slug" : "the-carolina-weddings-show",
"subject" : "The Carolina Weddings Show",
"date" : ISODate("2015-12-04T13:13:54.000+0000"),
"publisher" : {
"_id" : ObjectId("503b950fffa67e2c790007d7"),
"_slug" : "livingsocialcom",
"name" : "Livingsocial.com",
"taal" : "nl"
},
"hits" : NumberInt(1)
},
"5d4b29ad8ddf870fe15623f4" : {
"_id" : ObjectId("5d4b29ad8ddf870fe15623f4"),
"_slug" : "newport-gangster-tour",
"subject" : "Newport Gangster Tour",
"date" : ISODate("2015-12-04T13:13:22.000+0000"),
"publisher" : {
"_id" : ObjectId("503b950fffa67e2c790007d7"),
"_slug" : "livingsocialcom",
"name" : "Livingsocial.com",
"taal" : "nl"
},
"hits" : NumberInt(1)
},
"5d4b29bb8ddf870fe15628f3" : {
"_id" : ObjectId("5d4b29bb8ddf870fe15628f3"),
"_slug" : "springwise-daily-shoe-insoles-control-devices-through-kicking-and-more",
"subject" : "Springwise Daily | Shoe insoles control devices through kicking, and more.",
"date" : ISODate("2015-12-04T13:15:05.000+0000"),
"publisher" : {
"_id" : ObjectId("5581f0b54c7959e82bfd71c2"),
"_slug" : "springwise-com",
"name" : "springwise.com",
"taal" : "nl"
},
"hits" : NumberInt(2)
}
}
}
{
"_id" : ObjectId("5d4b4ca5a6bba5f7ffb23b3d"),
"bucket" : "last4hours",
"language" : "nl",
"time" : "2019-08-08_00",
"newsletters" : {
"5d4b29ba8ddf870fe15628c7" : {
"_id" : ObjectId("5d4b29ba8ddf870fe15628c7"),
"_slug" : "nieuwsbrief-dalstra-reizen-touring-december-2015",
"subject" : "Nieuwsbrief Dalstra Reizen Touring december 2015",
"date" : ISODate("2015-12-04T13:15:03.000+0000"),
"publisher" : {
"_id" : ObjectId("557ebcc54c79597761fd71c2"),
"_slug" : "dalstra-nl",
"name" : "dalstra.nl",
"taal" : "nl"
},
"hits" : NumberInt(1)
},
"5d4b29af8ddf870fe15624ba" : {
"_id" : ObjectId("5d4b29af8ddf870fe15624ba"),
"_slug" : "the-carolina-weddings-show",
"subject" : "The Carolina Weddings Show",
"date" : ISODate("2015-12-04T13:13:54.000+0000"),
"publisher" : {
"_id" : ObjectId("503b950fffa67e2c790007d7"),
"_slug" : "livingsocialcom",
"name" : "Livingsocial.com",
"taal" : "nl"
},
"hits" : NumberInt(1)
},
"5d4b29ad8ddf870fe15623f4" : {
"_id" : ObjectId("5d4b29ad8ddf870fe15623f4"),
"_slug" : "newport-gangster-tour",
"subject" : "Newport Gangster Tour",
"date" : ISODate("2015-12-04T13:13:22.000+0000"),
"publisher" : {
"_id" : ObjectId("503b950fffa67e2c790007d7"),
"_slug" : "livingsocialcom",
"name" : "Livingsocial.com",
"taal" : "nl"
},
"hits" : NumberInt(1)
},
"5d4b29bb8ddf870fe15628f3" : {
"_id" : ObjectId("5d4b29bb8ddf870fe15628f3"),
"_slug" : "springwise-daily-shoe-insoles-control-devices-through-kicking-and-more",
"subject" : "Springwise Daily | Shoe insoles control devices through kicking, and more.",
"date" : ISODate("2015-12-04T13:15:05.000+0000"),
"publisher" : {
"_id" : ObjectId("5581f0b54c7959e82bfd71c2"),
"_slug" : "springwise-com",
"name" : "springwise.com",
"taal" : "nl"
},
"hits" : NumberInt(2)
}
}
}
The goal here is to only have to query the bucket language time. So, if I want to see the trending newsletters of the last 2 hours, I query {bucket: 'last2hours', language: 'nl', time: '2019-08-08_00'}, then I have all the information I need. No need for aggregation. This findOne query is fast.
So i made a method to update the trending collection:
public function setNewsletterTrendingStatistics($newsletter){
// Buckets
$trend_buckets = array(
'last2hours' => array('steps' => 2, 'step'=>'hour', 'format'=> 'Y-m-d_H'),
'last4hours' => array('steps' => 4, 'step'=>'hour', 'format'=> 'Y-m-d_H' ),
'last1day' => array('steps' => 24, 'step'=>'hour', 'format'=> 'Y-m-d_H' ),
'lastweek' => array('steps' => 7, 'step'=>'day', 'format'=> 'Y-m-d' ),
'lastmonth' => array('steps' => 31, 'step'=>'day', 'format'=> 'Y-m-d' ),
);
// $newsletter['date']->toDateTime()->format('U')
$buckets = array();
foreach($trend_buckets AS $bucket => $settings){
for($i=0; $i<$settings['steps']; $i++){
$buckets[] = array(
'bucket' => $bucket,
'time' => date($settings['format'], strtotime('+'. $i . ' ' . $settings['step'])),
'language' => $newsletter['publisher']['taal'],
);
}
}
// Add the stats to each bucket
foreach($buckets AS $bucket){
$query = array();
$query = $bucket;
$update = array(
'$set' => array(
'newsletters.' . (string) $newsletter['_id'] . '._id' => $newsletter['_id'],
'newsletters.' . (string) $newsletter['_id'] . '._slug' => $newsletter['_slug'],
'newsletters.' . (string) $newsletter['_id'] . '.subject' => $newsletter['subject'],
'newsletters.' . (string) $newsletter['_id'] . '.date' => $newsletter['date'],
'newsletters.' . (string) $newsletter['_id'] . '.publisher' => array(
'_id' => $newsletter['publisher']['_id'],
'_slug' => $newsletter['publisher']['_slug'],
'name' => $newsletter['publisher']['name'],
'taal' => $newsletter['publisher']['taal'],
),
),
'$inc' => array(
'newsletters.' . (string) $newsletter['_id'] . '.hits' => 1
),
);
$options = array('upsert'=>true);
$this->FW->mdb->{$this->config['collections']['newsletters_trending']}->updateOne($query, $update, $options);
}
}
First of all, is this a good approach? Is there a better approach? Second, I want to count unique hits, so I need to save an IP address. I want to count unique hits on the update query so I don't have to count on the findOne query. Whats the best way to achieve this? I know I can use addtoset for a unique array with IP addresses. But then I need to count these unique IP addresses.
So i ended up doing this:
I made buckets for each trending container (last 2 hours, last 4 hours, today, last week, last month) for every hour.
I fill this containers on every pageview with an update query $inc 1.
Every hour a cronjob combines these stats. so 2 hours fill 4 hours 4 hours fill today etc.
This seems like the best approche and are live stats.
Hey guys Im a student and my question might seem simple but i can't find the right answer anywhere. Please take a look. as you can see $parsed_json works fine with this code $parsed_json = $parsed_json['photos']; how do i add another key of the array there? i tried $parsed_json = $parsed_json[(['photos']['contactInfo'])]; but did now work. Any help will much appreciated. Thank you.
<?php
$json_string = file_get_contents("api/goes/here")
$parsed_json = json_decode($json_string, true);
print_r($parsed_json);
$parsed_json = $parsed_json[(['photos']['contactInfo'])];
foreach($parsed_json as $key => $value)
{
echo $value['typeName'] . '<br>';
echo $value['typeId'] . '<br>';
echo $value['familyName'] . '<br>';
// etc
?>
-------------JSON CONTENT------------------------------
{
"status" : 200,
"requestId" : "0ef05ee4-6bab-4488-a80c-04ce050ca074",
"likelihood" : 0.95,
"photos" : [ {
"type" : "linkedin",
"typeId" : "linkedin",
"typeName" : "LinkedIn",
"url" : "https://d2ojpxxtu63wzl.cloudfront.net/static/651f183b3a1bd463ef5298a2877f2c4f_0c027087db5cd03d244a7dd42e42fc969fa8d636bffd7635b46172c8a597aa73",
"isPrimary" : true
}, {
"type" : "twitter",
"typeId" : "twitter",
"typeName" : "Twitter",
"url" : "https://d2ojpxxtu63wzl.cloudfront.net/static/d0080f4ccd9ea21340b0fd994f82c0e0_2acdc7de41111f7d58e7544ed970b78e72f1739784417c146d5689d96ce79137"
} ],
"contactInfo" : {
"familyName" : "Cassini",
"fullName" : "Flavio Cassini",
"givenName" : "Flavio"
},
"organizations" : [ {
"name" : "DEVTECH .LLC",
"startDate" : "2015-03",
"title" : "President/Owner",
"current" : true
} ],
"demographics" : {
"locationDeduced" : {
"normalizedLocation" : "Boca Raton, United States",
"deducedLocation" : "Boca Raton, Florida, United States",
"city" : {
"name" : "Boca Raton"
},
"state" : {
"deduced" : true,
"name" : "Florida",
"code" : "FL"
},
"country" : {
"name" : "United States",
"code" : "US"
},
"continent" : {
"deduced" : true,
"name" : "North America"
},
"county" : {
"deduced" : true,
"name" : "Palm Beach"
},
"likelihood" : 1.0
},
"gender" : "Male",
"locationGeneral" : "Boca Raton, Florida, United States"
},
"socialProfiles" : [ {
"type" : "klout",
"typeId" : "klout",
"typeName" : "Klout",
"url" : "http://klout.com/DevTechServices",
"username" : "DevTechServices",
"id" : "91760869707035580"
}, {
"followers" : 67,
"following" : 67,
"type" : "linkedin",
"typeId" : "linkedin",
"typeName" : "LinkedIn",
"url" : "https://www.linkedin.com/in/devtechservices",
"username" : "devtechservices",
"id" : "428935547"
}, {
"bio" : "Student at Full Sail University",
"followers" : 5,
"following" : 36,
"type" : "twitter",
"typeId" : "twitter",
"typeName" : "Twitter",
"url" : "https://twitter.com/DevTechServices",
"username" : "DevTechServices",
"id" : "3245620291"
} ],
"digitalFootprint" : {
"scores" : [ {
"provider" : "klout",
"type" : "general",
"value" : 48
} ],
"topics" : [ {
"provider" : "klout",
"value" : "Bitcoin"
}, {
"provider" : "klout",
"value" : "Content Marketing"
}, {
"provider" : "klout",
"value" : "SAAS"
}, {
"provider" : "klout",
"value" : "Software"
}, {
"provider" : "klout",
"value" : "WordPress"
} ]
}
}
The short answer is that if $parsed_json represents an associative array of associative arrays, then it stands to reason that $parsed_json['photos'] is an associative array itself. To access the 'contactInfo' value inside it, you simply use $parsed_json['photos']['contactInfo'].
How to print the Results from Google Distance matrix iam Getting a results like this:
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "4,8 km",
"value" : 4820
},
"duration" : {
"text" : "17 minutes",
"value" : 1038
},
"status" : "OK"
},
{
"distance" : {
"text" : "11,1 km",
"value" : 11064
},
"duration" : {
"text" : "25 minutes",
"value" : 1506
},
"status" : "OK"
}
]
}
],
And My Php Code to print The Output is
$json = file_get_contents($url);
$result = json_decode($json, true);
for($i=0; $i<count($result['rows']); $i++) {
echo "Kilometers " . $result['rows'][$i]["elements"][$i]['distance']['text'];
}
.Please Help
Given that you haven't included all the response, the method invlolved in the retrieval of the data nor the final desired output it is tricky to answer but I hope the following will give guidance on how to render the output.
This uses example data from the interwebs rather than the partial example code given in the question - a bit rough perhaps but...
$res='{
"destination_addresses" : [
"Commons Way, Bridgewater, NJ 08807, USA",
"Morris Turnpike, Short Hills, NJ 07078, USA",
"Monmouth Mall, Eatontown, NJ 07724, USA",
"Garden State Plaza Blvd, Paramus, NJ 07652, USA",
"Newport Centre Mall, Jersey City, NJ 07302, USA"
],
"origin_addresses" : [ "75 Ninth Ave, New York, NY 10011, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "68.8 km",
"value" : 68781
},
"duration" : {
"text" : "56 mins",
"value" : 3334
},
"duration_in_traffic" : {
"text" : "1 hour 1 min",
"value" : 3687
},
"status" : "OK"
},
{
"distance" : {
"text" : "34.8 km",
"value" : 34806
},
"duration" : {
"text" : "36 mins",
"value" : 2138
},
"duration_in_traffic" : {
"text" : "41 mins",
"value" : 2487
},
"status" : "OK"
},
{
"distance" : {
"text" : "86.3 km",
"value" : 86322
},
"duration" : {
"text" : "1 hour 6 mins",
"value" : 3930
},
"duration_in_traffic" : {
"text" : "1 hour 7 mins",
"value" : 4044
},
"status" : "OK"
},
{
"distance" : {
"text" : "32.3 km",
"value" : 32278
},
"duration" : {
"text" : "33 mins",
"value" : 2009
},
"duration_in_traffic" : {
"text" : "35 mins",
"value" : 2082
},
"status" : "OK"
},
{
"distance" : {
"text" : "6.9 km",
"value" : 6879
},
"duration" : {
"text" : "19 mins",
"value" : 1113
},
"duration_in_traffic" : {
"text" : "24 mins",
"value" : 1444
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}';
/* return as an object for easier notation */
$json=json_decode( $res, false );
$origins = $json->origin_addresses;
$destinations=$json->destination_addresses;
/* if there are multiple rows, use a loop and `$rows[$i]` etc */
$elements=$json->rows[0]->elements;
foreach( $elements as $i => $obj ){
echo '
<div>
<h5>From: '.$origins[ 0 ].' to '.$destinations[ $i ].'</h5>
Distance: '.$obj->distance->text.',
Duration:'.$obj->duration->text.',
In traffic: '.$obj->duration_in_traffic->text.',
Status: '.$obj->status.'
</div>';
}
Here is an example using a nested foreach, this is not the only way to render the output but it works.
$json = file_get_contents($url);
$result = json_decode($json, true);
foreach ($result['rows'][0] as $elements => $element) {
foreach ($element as $key => $value) {
echo $value['distance']['text'];
echo $value['duration']['text'];
echo $value['status'];
echo '<br>';
}
}
All we are doing is accessing a multi-dimensional array using $key => $value and then $value[$key] notation... I would suggest a crash course on how to handle arrays in php, this one is great: https://www.youtube.com/watch?v=57y5maglayQ
You can also look at the overall structure of your array by writing echo '<pre>', var_dump($result), '</pre>;' which will show your array => key pairs.
i am making a android application n use a .php file to call java script file that returns me a JSON output, now my problem is the output is in a valid JSON format, but i am confused as to how to parse the values. the output is
{
"destination_addresses" : [
"Kambarganvi road, Durgadakeri, Karnataka 580011, India",
"St Inez Road, Santa Inez, Panjim, Goa 403001, India",
"Dr Braganza Pereira Road, Santa Inez, Panjim, Goa 403001, India",
"Dayanand Bandodkar Marg, Santa Inez, Panjim, Goa 403001, India",
"St Inez Road, Santa Inez, Panjim, Goa 403001, India",
"18th June Road, Santa Inez, Panjim, Goa 403001, India"
],
"origin_addresses" : [ "Suyog Residency, St Joaquim Road, Borda, Margao, Goa 403602, India" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "133 km",
"value" : 132717
},
"duration" : {
"text" : "1 day 4 hours",
"value" : 100199
},
"status" : "OK"
},
{
"distance" : {
"text" : "33.4 km",
"value" : 33427
},
"duration" : {
"text" : "6 hours 54 mins",
"value" : 24832
},
"status" : "OK"
},
{
"distance" : {
"text" : "33.5 km",
"value" : 33518
},
"duration" : {
"text" : "6 hours 55 mins",
"value" : 24923
},
"status" : "OK"
},
{
"distance" : {
"text" : "33.8 km",
"value" : 33834
},
"duration" : {
"text" : "7 hours 0 mins",
"value" : 25170
},
"status" : "OK"
},
{
"distance" : {
"text" : "33.5 km",
"value" : 33503
},
"duration" : {
"text" : "6 hours 55 mins",
"value" : 24893
},
"status" : "OK"
},
{
"distance" : {
"text" : "33.5 km",
"value" : 33457
},
"duration" : {
"text" : "6 hours 55 mins",
"value" : 24880
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
i want to parse the values in such a way that i can place the distances of the result should be put in a data structure like an array and then sort them.
Thank you in advance.
use this to make own model .
http://www.jsonschema2pojo.org/
after making model you can use bwlow code.
Gson gson = new Gson();
gson.fromJson(jData, AddPostModel.class);
AddPostModel have all the data which comes from server.
This question already has an answer here:
Places Autocomplete API to get GPS coordinates from address entered
(1 answer)
Closed 8 years ago.
Suppose a very simple function to query Query Autocomplete:
$query_google_places = function ($input, array $location = null) {
$parameters = ['key' => 'AIzaSyAjCY7qYiaMv8Kkk_-D1Ha7wlRkr5neppk', 'input' => $input, 'sensor' => 'false'];
if ($location) {
$parameters['location'] = $location['lat'] . ',' . $location['lng'];
$parameters['radius'] = 10000;
}
$url = 'https://maps.googleapis.com/maps/api/place/queryautocomplete/json?' . \http_build_query($parameters);
$response = file_get_contents($url);
return $response;
};
This returns:
{
"predictions" : [
{
"description" : "Pizza Hut, Halifax, United Kingdom",
"id" : "d9274717e1e203c41287fa5936701b9584814965",
"matched_substrings" : [
{
"length" : 9,
"offset" : 0
}
],
"reference" : "CmRaAAAAyulRkdspSJ2Mr5kmlhYOC-ZT7AsKdnnwjGkFFoGHNjMWwTS5mNvQBu6FqoQ89E4U0eC-PNGN0wPD8WEYgO1if6jMmxWAqkraDFOryC8B8cWTvX333l_0UaRv_sXBIITqEhCSrz9aQB0fch-AFDS3wKG7GhTRoQw09IODWJIorqjjwCYTktkfKw",
"terms" : [
{
"offset" : 0,
"value" : "Pizza Hut"
},
{
"offset" : 11,
"value" : "Halifax"
},
{
"offset" : 20,
"value" : "United Kingdom"
}
],
"types" : [ "establishment" ]
},
{
"description" : "Pizza Hut, John William Street, Huddersfield, United Kingdom",
"id" : "a1571b1434ac1491b5f6775d9a30f8ec7798a310",
"matched_substrings" : [
{
"length" : 9,
"offset" : 0
}
],
"reference" : "CoQBdAAAADaFqqtB9NGk_v1yZdY3m6OxILfLva556GBHxHIVdPHu_R0fQCm5kCduCjKL4BgiIdoNIejet3WI7xNanaiWDpiMD1Ml7Q9EnfhypReK0N6mQIY3TxOUcmf_INhkenU3ZVL8Vk9lAxqjq5ZfxiEZk9Vv8GaEnok_OJnaRBuZdCmtEhAYs-0Qc2Zza4fLuUXIiLknGhQogPaBcUm10Y59EA5i6BWPbTNXcA",
"terms" : [
{
"offset" : 0,
"value" : "Pizza Hut"
},
{
"offset" : 11,
"value" : "John William Street"
},
{
"offset" : 32,
"value" : "Huddersfield"
},
{
"offset" : 46,
"value" : "United Kingdom"
}
],
"types" : [ "establishment" ]
},
{
"description" : "pizza hut",
"matched_substrings" : [
{
"length" : 9,
"offset" : 0
}
],
"terms" : [
{
"offset" : 0,
"value" : "pizza hut"
}
]
},
{
"description" : "Pizza Hut Delivery, Wakefield Road, Huddersfield, United Kingdom",
"id" : "0c6830de14a8e23bf971626e880201f5290ec9a6",
"matched_substrings" : [
{
"length" : 9,
"offset" : 0
}
],
"reference" : "CoQBeQAAAJnMKHhJh-IE64z6seh3sbnm4dt0h1zbMYLr4BPGCITQTZLp4lkm12HKEFw0Bt761UaZPsESrY4ha7XSXusqqRVstmRFBF2wiwF5HGMO9DhRSeIzJ8CkNvsxmlqINosGBBPUHEDQEeSOoPHn3u3MeByoLVw6AzZ9N6eTrm94hsX9EhBB9cIoXjhHjR9Tr3zBROM7GhRhpYagW9qWs9hGZ3V0o9WXfrfcXw",
"terms" : [
{
"offset" : 0,
"value" : "Pizza Hut Delivery"
},
{
"offset" : 20,
"value" : "Wakefield Road"
},
{
"offset" : 36,
"value" : "Huddersfield"
},
{
"offset" : 50,
"value" : "United Kingdom"
}
],
"types" : [ "establishment" ]
},
{
"description" : "Pizza Hut Delivery, Westgate, Halifax, United Kingdom",
"id" : "667c14a2cb5bb676bd02911e924db82fb5cbe6df",
"matched_substrings" : [
{
"length" : 9,
"offset" : 0
}
],
"reference" : "CnRtAAAAEtMYQ9N4Gmn8dpZqzHOxYGPCNP9QQ6M-gHjj2hJv2euH4gUVvDhmgazi6LcRjdYpUF41moGLr26IGc2vOPfvFg_kHTqTIYHHwiD84bu0PeEzmLzIzJw2IkGNpcW1o6weO86TW8zaUaMFZ2zNW-tynhIQFT8GvSn_q7DAoP3ytM14ExoUN3sShljpfaCWEUknvsfAjZJ_Ru4",
"terms" : [
{
"offset" : 0,
"value" : "Pizza Hut Delivery"
},
{
"offset" : 20,
"value" : "Westgate"
},
{
"offset" : 30,
"value" : "Halifax"
},
{
"offset" : 39,
"value" : "United Kingdom"
}
],
"types" : [ "establishment" ]
}
],
"status" : "OK"
}
How do I get coordinates for each result? Note, that this is server-side question.
IMO, autocompletion or query autocompletion results live in a different world than search results. Google assumes you're not supposed to need coordinates in the autocompletion list because this is not the data you will be presenting on your map or in any controller. The data you'll present will be the result of a true "search" request.
Conclusion: you're supposed to call again Google server on endpoints such as nearby search, text search or details to get the coordinates.
If you want to use details, if the user clicked on a prediction from autocomplete for example, you'll use reference attribute as a parameter of your http request to identify the clicked prediction.