need to read (echo) json by php - php

i need to get json code that changed remotely and display the data in php
when user load the page. (echo it)
i have this code:
(JSON output:)
{
"area 267":[
"city1",
"city2",
"city3",
"city4",
"city5",
"city6",
"city7",
"city8",
"city9",
"city10",
"city11",
"city12",
"city13"
],
"area 268":[
"city14",
"city15",
"city16"
],
"Coords":[
"31.856128;34.760947",
"31.8166376;34.729755",
"31.857223;34.727432",
"31.843444;34.751793",
"31.831039;34.722577",
"31.831504;34.756643",
"31.817725;34.7223",
"31.815936;34.752588",
"31.819054;34.739162",
"31.824913;34.747459",
";",
"31.813987;34.719103",
"31.833778;34.74009",
"31.815936;34.752589",
"31.819054;34.739163",
"31.824913;34.747458",
],
"ID":"1405796061262"
}
the coords lines is the sum of the all cities.
i need to echo the json like this:
(PHP output need to be like:)
ID: 1405796061262.
Areas: area267, area268.
Citys of Area267: city1, city2, ... city13. (echo all cities in the area)
Citys of Area268: city14, city15, city16. (echo all cities in the area)
i cant know the areas and the cities (that in the JSON file).
Thanks for helping :)
EDIT: WORKING CODE
<?php
$json_data = '{
"area 267":[
"city1",
"city2",
"city3",
"city4",
"city5",
"city6",
"city7",
"city8",
"city9",
"city10",
"city11",
"city12",
"city13"
],
"area 268":[
"city14",
"city15",
"city16"
],
"ID":"1405796061262"
}';
$data = json_decode($json_data);
//var_dump($data);
echo 'ID: ';
echo $data->ID;
echo '.<br>';
echo 'Areas: ';
$areas = array();
foreach ($data as $k => $v) {
if (strpos($k, 'ID') !== 0 && strpos($k, 'Coords') !== 0) {
$areas[] = $k;
}
}
echo implode(', ',$areas).'.<br /><br />';
foreach ($areas as $k => $v) {
echo "Cities of ".$v.': ';
$cities = array();
$cities = null;
foreach ($data->$v as $area) {
$cities[] = $area;
}
echo implode(', ',$cities).'.<br />';
}
?>

first you can use json_decode to convert the json output into php object then you can easily loop it and get the exact field value.
here is the documentation link:- http://php.net/manual/en/function.json-decode.php

Probably something like this should work
$data = json_decode($json_data);
echo 'ID '.$data['ID']."<br />";
echo 'Areas: ';
$areas = array();
foreach ($data as $k => $v) {
if (strpos($k, 'area ') === 0) {
$areas[] = $k;
}
}
echo implode(',',$areas).'.<br /><br />';
foreach ($areas as $area) {
echo "Cities of ".strtoupper($area).':';
$cities = array();
foreach ($data[$area] as $city) {
$cities[] = $city;
}
echo implode(','.$cities).'.<br />';
}

Related

Not able to parse nested Json array in PHP while print_r function is printing all values properly

I am trying to parse a json array string. Though print_r prints all the values properly but while fetching the records I failed.
I must be doing something very terribly wrong. Could you please help to correct it.
So here is my code
<?
$str ='
{
"tenant_view_details": [
{
"status":"S",
"tenant_general":[
{"tenant_id":"6003","code":"ICI001","type":"BANK","category":"SM","gstn":"IWSDFS7372","pan":"KSAH9876AS","cin":"ASHED456","name":"ICICI Bank","address_line_1":"23, Hertz Plaza, Rajiv Chowk","address_line_2":" ","address_city":"New Delhi","address_distict ":"New Delhi","address_state ":"DL","address_state_code ":"07","address_pin ":"119923","contact_name ":"contact_name","contact_phone ":"1234567890","contact_std_code ":"11","contact_landline ":"1234567890","contact_email_id ":"contact#email.com"} ],
"tenant_bank": [
{ "bank_name ":"xyz","bank_account_no ":"12345","account_type ":"abc","ifsc_code ":"xx123","address_line_1 ":"qwer","address_line_2 ":"23","address_city ":"abc","address_district ":"xyz","address_state_name ":"asd","address_state_code ":"02","address_pin ":"123456" } ],
"tenant_agreement": [
{ "category ":"OM","tenancy_type ":"EXT","echarge_type ":"FIX","total_tenancy_value ":"32900.00","energy_charge_value ":"16543.00","rev_share_pct ":"0.05","start_dt":"10-1-2018","end_dt":"31-12-2020","attachment_path ":"na","change_value ":"na","latest_flag ":"Y","w_status ":"20","status ":"ACT"} ],
"tenant_sites": [
{"tenant_id":"6003","site_master_id":"1020","tn_site_code":"UPWMORA00069473","tn_site_name":"Deendayal Nagar","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"MAST","site_type":"ID","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1019","tn_site_code":"UPWGHAZ00069467","tn_site_name":"DJ College Newari Road, Modina","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"MAST","site_type":"ID","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1018","tn_site_code":"UPWMORA00069464","tn_site_name":"Bazar Makhbra","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"OD","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1016","tn_site_code":"UPWGHAZ00069454","tn_site_name":"Hoshdarpur Garhi","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"OD","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1011","tn_site_code":"UPWMUZN00069430","tn_site_name":"Sikanderpur","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"ID","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"}, {"tenant_id":"6003","site_master_id":"1008","tn_site_code":"UPWALIG00069299","tn_site_name":"Mukund Vihar","tn_cluster":"CLUSTER-03","circle_code":"UW","tower_type":"RTT","site_type":"","tenancy_type":"EXT","echarge_type":"FIX","primary_tenant":"N","latest_flag ":"Y"} ]
}
]
}
';
$dataset = json_decode($str, true);
//print_r ($dataset);
foreach ($dataset['tenant_view_details'] as $newdata) {
$general = $newdata['tenant_general'];
$bank = $newdata['tenant_bank'];
$agreement = $newdata['tenant_agreement'];
$sites = $newdata['tenant_sites'];
}
//prinitng data
echo "<br/>";
print_r($general);
echo "<br/>";
print_r($bank);
echo "<br/>";
print_r($agreement);
echo "<br/>";
foreach($general as $general_data){
(isset($general_data['tenant_id']) && !empty($general_data['tenant_id']))? $tenant_id=$general_data['tenant_id'] : $tenant_id="not set";
echo "<br/>tenant_id::" . $tenant_id;
}
foreach($bank as $bank_data){
(isset($bank_data['bank_name']) && !empty($bank_data['bank_name']))? $bank_name=$bank_data['bank_name'] : $bank_name="not set";
echo "<br/>bank_name:" . $bank_data['bank_name'];
}
foreach($agreement as $agreement_data){
(isset($agreement_data['category']) && !empty($agreement_data['category']))? $category=$agreement_data['category'] : $category="not set";
(isset($agreement_data['tenancy_type']) && !empty($agreement_data['tenancy_type']))? $tenancy_type=$agreement_data['tenancy_type'] : $tenancy_type="not set";
(isset($agreement_data['echarge_type']) && !empty($agreement_data['echarge_type']))? $echarge_type=$agreement_data['echarge_type'] : $echarge_type="not set";
echo "<br/>category:" . $category;
echo "<br/>tenancy_type:" . $tenancy_type;
echo "<br/>echarge_type:" . $echarge_type;
}
?>
Your problem is that in your $bank and $category arrays, all the keys have trailing spaces on them. If you change the references to include those spaces, your code works fine. See https://3v4l.org/GX5iC
Alternatively you can trim the array keys, using something like this code inside your foreach loops:
$bank_keys = array_map('trim', array_keys($bank_data));
$bank_data = array_combine($bank_keys, array_values($bank_data));
You could also create a recursive function to trim the entire $dataset value. For example:
function trim_keys($array) {
foreach ($array as $key => $value) {
echo "trimming key '$key' to '" . trim($key) . "'\n";
unset($array[$key]);
$array[trim($key)] = $value;
if (is_array($value))
$array[trim($key)] = trim_keys($value);
else
$array[trim($key)] = $value;
}
return $array;
}
Then, by using
$dataset = trim_keys($dataset);
Your code will work fine. Demo on 3v4l.org

How to get json property name with php

So here's the thing, I get this json from a url ( in my context i get it from a url, but let's say here I write my json in a variable :
$file = '[
{"status": "5.4.1","email": "dddddd#exelcia-it.com"},
{"status": "5.4.1",, "email": "sksksksk#exelcia-it.com"}
]'
Then I do $json = json_decode($file,true);
And I want to get all the emails so I do :
foreach ($json as $key => $value) {
echo $value["email"]. "<br>";
}
But what I also need, is to return something like that from the loop (only for one property):
"email = dddddd#exelcia-it.com".
So I need to also get the name of the property but I can't figure this out.
I tried
foreach($json as $key => $propName){
echo $key.'<br>';
}
But I just get the index (0,1,...), not what I want.
Thanks!
You have to loop each json row, this should works:
$file = '[{"status": "5.4.1","email": "dddddd#exelcia-it.com"},{"status": "5.4.1", "email": "sksksksk#exelcia-it.com"}]';
$json = json_decode($file,true);
foreach($json as $row)
{
foreach($row as $key => $value)
{
echo "<b>".$key."</b>".':'.$value.'<br>';
}
}
Use this loop to get key and value pairs together.
foreach($data as $row)
{
foreach($row as $key => $val)
{
echo $key . ': ' . $val;
echo '<br>';
}
}
Ok thanks that's what I needed !
For me I just need the email properties and values, so I do :
foreach($json as $row)
{
foreach($row as $key => $value)
{
if($key=='email'){
echo "<b>".$key."</b>".':'.$value.'<br>';
}
}
}
Awesome ! thanks !

Json data group by team name with php

I have to display team points under respective team name
I have following json data
{
"id":319231,
"innings":[
{"id":967766},
{"id":967767},
{"id":967768},
{"id":967769}
],
"team1":{
"team":{"name":"Minor Counties","id":115104,"club":{"name":"Minor Counties","id":98110}},
"innings":[
{"id":967766,"points":253,"wickets":10,"overs":86,"balls":4},
{"id":967768,"points":190,"wickets":5,"overs":61,"balls":0}
]
},
"team2":{
"team":{"name":"Major Counties","id":93648,"club":{"name":"Major Counties","id":35487}},
"innings":[
{"id":967767,"points":229,"wickets":10,"overs":67,"balls":4},
{"id":967769,"points":64,"wickets":4,"overs":23,"balls":2}
]
},
}
Now I want result like :
Minor Counties Major Counties
253/10 & 190/5 229/10 & 64/4
Currently I am getting result like :
Minor Counties Minor Counties Major Counties Major Counties
253/10 190/5 229/10 64/4
Here is my php code so far :
$team1 = $read_json->team->team1->name;
$team2 = $read_json->team->team2->name;
foreach($read_json->team1->innings as $team1Innings){
$points = $team1Innings->points;
$wickets = $team1Innings->wickets;
$overs = $team1Innings->overs;
$balls = $team1Innings->balls;
echo "<div class=\"score-total\"><span class=\"score-team\">$team1</span>$points/$wickets<span class=\"score-overs\">$overs.$balls overs</span></div>";
}
similar code to get team2 points
$json = '{
"id":319231,
"innings":[
{
"id":967766
},
{
"id":967767
},
{
"id":967768
},
{
"id":967769
}
],
"team1":{
"team":{
"name":"Minor Counties",
"id":115104,
"club":{
"name":"Minor Counties",
"id":98110
}
},
"innings":[
{
"id":967766,
"points":253,
"wickets":10,
"overs":86,
"balls":4
},
{
"id":967768,
"points":190,
"wickets":5,
"overs":61,
"balls":0
}
]
},
"team2":{
"team":{
"name":"Major Counties",
"id":93648,
"club":{
"name":"Major Counties",
"id":35487
}
},
"innings":[
{
"id":967767,
"points":229,
"wickets":10,
"overs":67,
"balls":4
},
{
"id":967769,
"points":64,
"wickets":4,
"overs":23,
"balls":2
}
]
}
}';
$items = json_decode($json);
unset($items->id);
unset($items->innings);
foreach ($items as $item) {
echo "<b>{$item->team->name}</b>";
$innings = [];
foreach ($item->innings as $inning) {
$innings[] = "{$inning->points} / {$inning->wickets}";
}
echo '<br>';
echo implode(' & ', $innings);
echo '<br>';
}
Use json_decode() with true as second parameter it gives you an associative array and it will convert the JSON object into a PHP object.It will make your life easier.
Try this :
$jsonObj = json_decode($json,true);
$inningsPoint = [];
foreach ($jsonObj as $teamData) {
if(!empty($teamData[team][name])) {
echo $teamData[team][name].'<br>';
$inningsPoint = [];
}
foreach ($teamData[innings] as $inningsData) {
$inningsPoint[] = "$inningsData[points] / $inningsData[wickets]";
}
echo implode(' & ', $inningsPoint);
}
Demo!
<?php
function showteams_results($k1,$points){
switch ($k1) {
case 'team1':
foreach ($points as $key => $value) {
if($key=="team1")
{
echo ucfirst($key)."<br>";
foreach ($value as $k => $v) {
echo "Innings".$v."<br>";
}
}
}
break;
case 'team2':
foreach ($points as $key => $value) {
if($key=="team2")
{
echo ucfirst($key)."<br>";
foreach ($value as $k => $v) {
echo "Innings".$v."<br>";
}
}
}
break;
default:
echo "Team no points!";
break;
}
}
$points=array();
$jsonObj = json_decode($json,true);
$inningsPoint = [];
foreach ($jsonObj as $k1 => $teamData) {
//extracting points of team1---------->
if($k1=="team1"){
//showteams_results($k,$jsonObj);
foreach ($teamData as $k => $v) {
if($k=="innings")
{
foreach ($v as $k => $vf) {
foreach ($vf as $k => $vk) {
if($k=="points")
$points["team1"][]=$vk;
}
}
}
}
//sending data teams
showteams_results($k1,$points);
}
//extracting points of team2---------->
if($k1=="team2"){
//showteams_results($k,$jsonObj);
foreach ($teamData as $k => $v) {
if($k=="innings")
{
foreach ($v as $k => $vf) {
foreach ($vf as $k => $vk) {
if($k=="points")
$points["team2"][]=$vk;
}
}
}
}
//sending data teams
showteams_results($k1,$points);
}
}
?>

How to get more than 20 results for nearby places using google api

<?php
{
$references = array();
$names = array();
$lat="26.177194999999998";
$long="91.77591333333334";
$count=0;
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
foreach ($names as $name) {
echo $name."<br>";
}
echo "next token".$dataArray->next_page_token."<br>";
if(!empty($dataArray->next_page_token)) {
echo "in the if statement"."<br>";
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw&nextpage=".$dataArray->next_page_token;
$placeSearchJSON = file_get_contents($placeSearchURL);
//echo "hello";
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
echo "hello<br>";
}
foreach ($names as $name) {
echo $name."<br>";
}
echo "next token".$dataArray->next_page_token."<br>";
if(!empty($dataArray->next_page_token)) {
echo "in the if statement"."<br>";
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw&nextpage=".$dataArray->next_page_token;
$placeSearchJSON = file_get_contents($placeSearchURL);
//echo "hello";
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
echo "hello<br>";
}
foreach ($names as $name) {
echo $name."<br>";
}
?>
I get the same 20 results every time, and I have used pagination as you can see in my code. Every time I print the next page token I get a different one.
I would really appreciate if someone could point out the error in my code because I am stuck with this for quite some time. You are also most welcome to give any kind of relevant suggestion.
use pagetoken instead of nextpage in your url string and in the last two calls give only api key and page token as parameter and after each api call use sleep(2) i tried your code and it works perfectly when the following changes are made.happy coding!
<?php
//echo"hello";
$references = array();
$names = array();
$lat="26.177194999999998";
$long="91.77591333333334";
$count=0;
$placeSearchURL ="https://maps.googleapis.com/maps/api/place/radarsearch/json?location=26.177194999999998,91.77591333333334&radius=3000&types=mosque&key=your APIkey";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
foreach( $dataArray->results as $details) {
//echo $details->place_id;
array_push($references, $details->place_id);
}
foreach($references as $reference)
{
$count=$count+1;
//echo $count." ";
$placeSearchURL="https://maps.googleapis.com/maps/api/place/details/json?placeid=".$reference."&key=your apikey";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
echo $dataArray->result->name."<br>";
echo "lat ".$dataArray->result->geometry->location->lat."<br>";
echo "lon ".$dataArray->result->geometry->location->lng."<br>";
echo "address ".$dataArray->result->formatted_address."<br>";
echo "<br>";
}
?>
basically i wanted to find a way to get more than 20 places of type masjid so i first used radar search to get placeids and then for each placed_id got the information and best part is you can get arount 200 results of nearby places

PHP - How to Loop through JSON array with fields starting with "$"

I have been trying to workout how to loop through and output the contents of a json file where field names start with "$" and keep getting an Undefined variable error message
Here is an example of the json file example (taken from https://mixpanel.com/help/reference/webhooks):
[
{
"$distinct_id":"13b20239a29335",
"$properties":{
"$region":"California",
"$email":"harry.q.bovik#andrew.cmu.edu",
"$last_name":"Bovik",
"$created":"2012-11-20T15:26:16",
"$country_code":"US",
"$first_name":"Harry",
"Referring Domain":"news.ycombinator.com",
"$city":"Los Angeles",
"Last Seen":"2012-11-20T15:26:17",
"Referring URL":"http://news.ycombinator.com/",
"$last_seen":"2012-11-20T15:26:19",
}
},
{
"$distinct_id":"13a00df8730412",
"$properties":{
"$region":"California",
"$email":"anna.lytics#mixpanel.com",
"$last_name":"Lytics",
"$created":"2012-11-20T15:25:38",
"$country_code":"US",
"$first_name":"Anna",
"Referring Domain":"www.quora.com",
"$city":"Mountain View",
"Last Seen":"2012-11-20T15:25:39",
"Referring URL":"http://www.quora.com/What-...",
"$last_seen":"2012-11-20T15:25:42",
}
}
]
I am testing with a static string just to try and get things working. Here is my test code...
<?php
$input = '[{"$distinct_id":"13b20239a29335","$properties":"dddd"}]';
$jsonObj = json_decode($input, true);
foreach ($jsonObj as $item) {
foreach ($item as $rec) {
echo '<br>';
$my_id = $rec->$distinct_id;
echo($my_id);
$my_id = $rec->$properties;
echo($my_id);
}
echo '<br>';
}
?>
Any help would be appreciated.
Noob!
UPDATE: Musa gave this example which works for the single level json:
foreach ($jsonObj as $item) {
echo '<br>';
$my_id = $item->{'$distinct_id'};
echo($my_id);
$my_id = $item->{'$properties'};
echo($my_id);
echo '<br>';
}
How can this then be adapted to read and output all elements of the bigger multi-level json file?
Use Curly bracket notation
$object->{'$property'};
Edit
foreach ($jsonObj as $item) {
echo '<br>';
$my_id = $item->{'$distinct_id'};
echo($my_id);
foreach ($item->{'$properties'} as $my_prop => $value){
echo("$my_prop => $value");
}
echo '<br>';
}
http://codepad.org/1cudZqlu
With the nested loop you're iterating the properties $distinct_id and $properties so $rec is actually a string and not an object.
Also your json is invalid as it has trailing , in the $properties field.

Categories