PHP Traverse through JSON using foreach - php

I had been following this guide to create an app using two different APIs but the guide is old and so one of the APIs does not work like it did in the guide. I am trying to grab coordinates from google geocoding API and stick them into Places for Web. I am new to PHP, so I was following the guide's example to traverse a JSON object but have been stuck all night trying to get it to work.
Here is the JSON object from the place search API
{
"html_attributions":[ ],
"results":[
{
"geometry":{ },
"icon":"https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id":"d4b0fb0f7bf5b2ea7df896a0c120a68efae039cf",
"name":"Guadalajara Mexican Grill & Cantina",
"opening_hours":{ },
"photos":[
{
"height":2952,
"html_attributions":[ ],
"photo_reference":"CmRaAAAAfO4JKUaO8vCFM2dcu5LMu4mA4_HXQGJ1FyAnyJUre_kD6VOWiQj7tBEECx4AAct5AORIKipSYWg-Zprjlf8o-SFd7mBRGMXMVMwodFZ5KMLwPYPUhBnTTehGPkb9275pEhCkAqMwfmK29vYenk1wdwFvGhSIHR8ch6FONc99tGn4rVnesbuteg",
"width":5248
}
],
"place_id":"ChIJ27es4SWa3IARcvjmt3xL2Aw",
"price_level":2,
"rating":4.4,
"reference":"CmRRAAAA7Rx-l7juDX-1or5dfpK6qFcZ0trZ9cUNEUtKP2ziqHb2MhOE6egs-msJ2OdFKEuHhuNe-3Yk6yxUYwxCBqhDT3ci8pYZI4xYhPGyyDgDenbEU_8k84JiEtCGvj4bdIR0EhDR2Pqte5_kDUcCC9PJFVknGhQomvD4d7NBIhCFxI4i2iEc0w9UiA",
"scope":"GOOGLE",
"types":[ ],
"vicinity":"105 North Main Street, Lake Elsinore"
},
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ }
],
"status":"OK"
}
I am trying to grab all the photo references into an array maybe?, and then plug them into google's Place Photos API. Here is my attempt at that:
UPDATE
<?php
if(!empty($_GET["location"])){
//$API_key = "";
$maps_url = 'https://' .
'maps.googleapis.com/' .
'maps/api/geocode/json' .
'?address=' . urlencode($_GET['location']) .
'&key=';
$maps_json = file_get_contents($maps_url);
$maps_array = json_decode($maps_json, true);
$lat = $maps_array['results'][0]['geometry']['location']['lat'];
$lng = $maps_array['results'][0]['geometry']['location']['lng'];
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
'location=$lat,$lng' .
'&radius=1500' .
'&rankby=distance' .
'&key=';
$places_json = file_get_contents($places_url);
$places_array = json_decode($places_json, true);
if (!empty($places_array)) {
foreach ($places_array as $item) {
var_dump($places_array );
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>What is Here?</title>
</head>
<body>
<h1>Type in a location</h1>
<p>This program will display pictures of places to go in that area</p>
<form action ="">
<input type ="text" name ="location"/>
<button type ="submit">Go!</button>
</form>
<br/>
<?php
echo "$lat $lng";
?>
Just can't seem to get the foreach loop to do anything

the invalid request means wrong url or bad parameters
if $lat and $lng are variables then the interpolation wont work with single quotes try using double quotes like this
"location=$lat,$lng"
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
"location=$lat,$lng" .
'&rankby=distance' .
'&key=mykey';
you should remove radius or distance you cant get both its on the docs
https://developers.google.com/places/web-service/search?hl=en-419
here is my modified code that works on localhost please notice the $contextOptions you should not copy this on your code this is a workaround to make file_get_contents work on my machine
after that the foreach should be easy since is only an array look at the code
$thelocation = "1600+Amphitheatre+Parkway,+Mountain+View,+CA";
$thekey = "someapikey";
$maps_url = 'https://' .
'maps.googleapis.com/' .
'maps/api/geocode/json' .
'?address=' . urlencode($thelocation) .
'&key=' . $thekey;
$contextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
),
);
$maps_json = file_get_contents($maps_url, 0, stream_context_create($contextOptions));// file_get_contents($maps_url);
$maps_array = json_decode($maps_json, true);
$lat = $maps_array['results'][0]['geometry']['location']['lat'];
$lng = $maps_array['results'][0]['geometry']['location']['lng'];
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
"location=$lat,$lng" .
'&rankby=distance' .
'&key='.$thekey;
//https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&rankby=distance&key=
$places_json = file_get_contents($places_url,0, stream_context_create($contextOptions));
$places_array = json_decode($places_json, true);
if (!empty($places_array)) {
foreach ($places_array["results"] as $item) {
echo $item["name"]."<br>";
}
}
this prints....easy
AVEonline.co
KRAV MAGA GLOBAL WORLD MAP
Mark Carvalho
Amyan
Moving the Planet
Sosta in Camper
NosCode
GLOBAL BUZZ
OptiClean
JI-SU TELECOM
Reel Thrillz
Clío Reconstrucción Histórica
AprimTek
Hayjayshop
NHAV
gitanos.cat
Being Digitall
Directory+
AdExperts
Optical Spectroscopy and Nanomaterials Group

The $lat,$lng variables or the API call is your first problem, and the foreach loop is the second.
The json_decode($someJSON, true); creates an associative array from your json, so you can't use the -> arrows, those are for the objects. More about this.
There's no $item->photo_reference, use:
$results = $places_array["results"];
foreach ($results as $item) {
echo $item["photos"]["photo_reference"];
}

Related

PHP Sort results from key values inside multiple json files

is it possible to sort the results by key value inside separate json files?
I need to sort the result by "id" value.
Sorry if this is a duplicate but I've searched entire internet and couldn't find a solution.
Many thanks for your help.
<div class="container grid grid-cols-2 gap-6 tablet:grid-cols-3 desktop:grid-cols-6">
<?php
$i = 0;
$dir = (new DirectoryIterator(__DATA_PAGES_PATH__ . 'products/content/' . $lang));
foreach ($dir as $productsdata) {
if ($productsdata->isDot()) continue;
$productdata = json_decode(file_get_contents(__DATA_PAGES_PATH__ . 'products/content/' . $lang . "/" . $productsdata));
if ($productdata->popular > 0) {
?>
<?php echo $productdata->id ?>
<?php
};
if (++$i == 6) break;
}
?>
</div>
Content of multiple json files inside the directory:
{
"id": 0,
"name": "prd-name-0",
"category": "prd-category-0"
}
{
"id": 1,
"name": "prd-name-1",
"category": "prd-category-1"
}
So this was my solution for anyone who might need this. thanks to #CBroe
function sortkey($folder, $key)
{
$GLOBALS['files'] = glob(__data__ . $folder . '/' . $GLOBALS['lang'] . '/*.json');
$GLOBALS['sort'] = [];
foreach ($GLOBALS['files'] as $GLOBALS['file']) {
$GLOBALS['thisData'] = file_get_contents($GLOBALS['file']);
$GLOBALS['thisDataArr'] = json_decode($GLOBALS['thisData']);
if (isset($GLOBALS['thisDataArr']->$key)) {
$GLOBALS['sort'][$GLOBALS['thisDataArr']->$key] = basename(str_replace('.json', '', $GLOBALS['file']));
}
}
ksort($GLOBALS['sort']);
// var_dump($GLOBALS['sort']);
}

RGraph, Multiple Graphs with data from a PHP/MySQL source

iam trying to show multiple Graphs in one diagram. The datasource is a MySQL database which is connected via PHP.
My Problem: I cant figure out how to add the data to the RGraph Script. I managed to show one graph via PHP, bt i cant add a seconde one.
This is how i succsessfully get the Data (After connecting to the Database ofc.):
Important!: (At least i guess it is) i have two different cases, in one Case the return Data is a single Number (eg: "2") in my seconde case it is an array of 52 different numbers.
$1 = mysql_query("SELECT * FROM Table WHERE spalte1 ='XX' AND spalte2 ='XX' ORDER BY Datum DESC Limit 1");
if ($1) {
$labels = array();
$data = array();
while ($row = mysql_fetch_assoc($1)) {
$labels[] = $row["datum"];
$2[] = $row["max"];
}
// Now you can aggregate all the data into one string
$2_string = "[" . join(", ", $2) . "]";
$labels_string = "['" . join("', '", $labels) . "']";
}
else
{
print('MySQL query failed with error: ' . mysql_error());
}
This is how i draw the Graph:
<canvas id="cvs" width="1200" height="250">[Browser not supported]</canvas>
<script>
//window.onload = function ()
//{
new RGraph.Line({
id:'cvs',
data:[<?php print($2_string) ?>],
options: {
colors:['#B71A1A'],
backgroundGrid: true,
//xaxisLabels: [<?php print($labels_string) ?>],
//xaxisLabelsAngle: 25,
xaxis: true,
yaxis: true,
yaxisScale: true,
yaxisScaleUnitsPost:'%',
yaxisScaleMax: 100,
title: 'XX',
textAccessible: true,
key: ['XX'],
keyPosition: 'margin',
keyPositionX: 25,
}
}).draw();
But how can i add a seconde graph into this diagram? All the Demos say something like:
data = [[1,2,3],[4,5,6]]
So i tryed different versions (just one example):
data = [[<?php print($1_string) ?>],[<?php print($2_string) ?>]]
Hopefully someone has an Idea ... :)
Thx for every try :)
Here is what I sent Simon via email
<?php
$1_data = 5;
$2_data = array(2,3,8 4,6,8,6,9,8,7,5,8);
// Make JavaScript arrays out of the above number and PHP array
// also making an array of two numbers out of the single number
$1_string = '[' . join(',', array($1_data, $1_data) . ']';
$2_string = '[' . join(',', $2_data) . ']';
?>
<canvas id="cvs" width="1200" height="250">[Browser not supported]</canvas>
<script>
new RGraph.Line({
id:'cvs',
data:[
<?php print($1_string) ?>,
<?php print($2_string) ?>
],
options: {
}
}).draw();
</script>

How to Read this JSON in PHP

I have a simple JSON and want to read in PHP. I am certainly missing something in array, can anybody point out my mistake. Its been considerable time I am playing with this simple thing.
Here is the JSON & php :
$string='[
{
"phone":"+91009999000",
"name":"abcd",
"typeid":1
}
{
"phone":"+91009999222",
"name":"efg",
"typeid":2
}
{
"phone":"+91009999444",
"name":"hijhl",
"typeid":1
}
]';
$json_a = json_decode($string,true);
$phone = $json_a[0]['phone'];
$full_name=$json_a[0]['courseid'];
echo "phone = " . $phone;
echo "<br>fullname = " . $full_name;
You are missing commas near curly braces.
It should be like this:
$string='[
{
"phone":"+91009999000",
"name":"abcd",
"typeid":1
},
{
"phone":"+91009999222",
"name":"efg",
"typeid":2
},
{
"phone":"+91009999444",
"name":"hijhl",
"typeid":1
}
]';

Parsing JSON with json_decode in PHP

This is the JSON data I get from our ticket-system. I would like to parse it with PHP and save the data in a database to create statistics and a dashboard so everyone can see how many tickets are open and the latest closed tickets.
I can read some of the data but not everything.
{
"address":"belgium",
"workers":{
"peter":{
"worker":"peter",
"open_close_time":"45.6 T/h",
"closed_tickets":841,
"open_tickets":7,
"last_checkin":1498768133,
"days_too_late":0
},
"mark":{
"worker":"mark",
"open_close_time":"45.9 T/h",
"closed_tickets":764,
"open_tickets":2,
"last_checkin":1498768189,
"days_too_late":0
},
"walter":{
"worker":"walter",
"open_close_time":"20.0 T/h",
"closed_tickets":595,
"open_tickets":4,
"last_checkin":1498767862,
"days_too_late":0
}
},
"total_tickets":2213,
"tickets":[
{
"id":2906444760,
"client":"297",
"processed":0
},
{
"id":2260,
"client":"121",
"processed":0
},
{
"id":2424,
"client":"45",
"processed":0
}
],
"last_closed_tickets":[
{
"id":2259,
"client":"341",
"closed_on":"2017-06-25T10:11:00.000Z"
},
{
"id":2258,
"client":"48",
"closed_on":"2017-06-20T18:37:03.000Z"
}
],
"settings":{
"address":"belgium",
"email":"",
"daily_stats":0
},
"open_close_time":"161.1 T/h",
"avgopen_close_time":123298,
"ticket_time":"27.1 T/h",
"stats":{
"time":1498768200087,
"newest_ticket":1498768189000,
"closed_tickets":2200,
"open_tickets":13,
"active_workers":3
},
"avg_paid_tickets":64.55,
"avg_afterservice_tickets":35.45
}
This is the PHP code I tried to get the names of the worker but this doesn't work.
<?php
$string = file_get_contents("example.json");
$json = json_decode($string, true);
echo $json['address'];
foreach($json->workers->new as $entry) {
echo $entry->worker;
}
?>
If I try it like here below it works but then I've got to change the code everytime another employee starts.
echo $json['workers']['mark']['closed_tickets'];
<?php
$string = file_get_contents("example.json");
$json = json_decode($string, true);
foreach($json['workers'] as $entry){
echo $entry['worker'] . " has " . $entry['open_tickets'] . " tickets" . "\n";
}
?>

How to append the two lines string in php json response

{
"employees": [{
"name": "Chicken Shawarma",
"price": "510.00",
"nutrients": "A
B "
}]
}
this is the my json response , In My app i setup a two line record for "nutrients". Ex :
A
B
this vale saved in database without any issue (My SQL), now i want display the "nutrients" data as a two line record. but its displaying below error
SyntaxError: unterminated string literal
if you have any idea please share with me.
this is the my server side code
if ($itemInfo->num_rows() == 1) {
$row = $itemInfo->row_array();
$json_arr = $_GET['callback'] . '(' .
"{'name' : '" . $row['name'] . "',"
. "'nutrients' : '" . $row['nutrients'] . "',"
. "'img' : '" . $row['img'] . "'}" . ')';
} else {
$json_arr = json_encode(array('status' => 'N'));
}
echo $json_arr;
this is the my client side code
$http.jsonp(full_url).success(function (data) {
$scope.item = data ;
});
Your main problem is making a JSON response by concatenating strings. In such case you miss required encodings/escaping and so on. So, first of all you should create an associative array and then do $json_arr = $_GET['callback'].'('.json_encode($your_json_like_array).')'; exactly like in the else clause.
Resulting code should look like this:
$json_arr = array(
'name' => $row['name'],
...,
'nutrients' => $row['nutrients']
);
$json_arr = $_GET['callback'].'('.json_encode($json_arr).')';

Categories