For Google Visualization I coded the JSON by hand (Messy I know) I did not think about ''s in NAME_TEAM which has recently come about an issue as my first team name was entered with an apostrophe. I have read this post and tried to implement php json_encode. I am having an issue with the dates. The new Date works fine in the old messy json format, however I get an error Fatal error: Class 'Date' when I try use anything similar for the Json_encode version. The format must be date for the visualization api to understand the values.
foreach ($data as $row) {
$dateArray = explode('-', $row['THE_DATE']);
$year = $dateArray[0];
$month = $dateArray[1] - 1;
$day = $dateArray[2];
$dataArray[] = "[new Date ($year, $month, $day), {$row['ORANGE']}, {$row['GREEN']}, '{$row['NAME_TEAM']}']";
$itemOutput[] = array(
new Date($year, $month, $day),
$row['ORANGE_SCORE'],
$row['GREEN_SCORE'],
$row['NAME_TEAM'],
);
}
echo "data.addRows(" . json_encode($itemOutput) . ");" ;
Data Table creation
function drawDashboard() {
//var data = new google.visualization.DataTable();
var data = new google.visualization.DataTable(<?php echo json_encode($itemOutput, JSON_NUMERIC_CHECK); ?>);
data.addColumn('date', 'Date');
data.addColumn('number', 'ORANGE_SCORE');
data.addColumn('number', 'GREEN_SCORE');
data.addColumn('string', 'NAME_TEAM');
// data.addRows(<?php echo '[' . implode(',', $dataArray) . ']'; ?>);
ARRAY FORMAT
{"c":[
{"Date":"new Date(2013, 9, 19)"},
{"ORANGE_SCORE":14},
{"GREEN_SCORE":7},
{"NAME_TEAM":"Trigon"}]
},
You can't use Date objects in JSON; the only way to transmit dates is via strings, but the DataTable.addRows method does not parse strings into Date objects, so you will have to convert to the full JSON structure to make this work. Here's an example:
$itemOutput = array(
'cols' => array(
array('type' => 'date', 'label' => 'Date'),
array('type' => 'number', 'label' => 'ORANGE_SCORE'),
array('type' => 'number', 'label' => 'GREEN_SCORE'),
array('type' => 'string', 'label' => 'NAME_TEAM')
),
'rows' => array()
);
foreach ($data as $row) {
$dateArray = explode('-', $row['THE_DATE']);
$year = $dateArray[0];
$month = $dateArray[1] - 1;
$day = $dateArray[2];
$itemOutput['rows'][] = array('c' => array(
array('v' => "Date($year, $month, $day)"),
array('v' => $row['ORANGE_SCORE']),
array('v' => $row['GREEN_SCORE']),
array('v' => $row['NAME_TEAM'])
));
}
Then in javascript:
var data = new google.visualization.DataTable(<?php echo json_encode($itemOutput, JSON_NUMERIC_CHECK); ?>);
If case 1 or 2, What do you want?
result is Case 2.
result link
source link
<?
/***
CREATE TABLE `24992408` (
`THE_DATE` TIMESTAMP NOT NULL DEFAULT DATE ,
`ORANGE` VARCHAR( 50 ) NOT NULL ,
`ORANGE_SCORE` INT( 11 ) NOT NULL ,
`GREEN` VARCHAR( 50 ) NOT NULL ,
`GREEN_SCORE` INT( 11 ) NOT NULL ,
`NAME_TEAM` VARCHAR( 50 ) NOT NULL
) ENGINE = MYISAM ;
INSERT INTO `24992408` (
`THE_DATE` ,
`ORANGE` ,
`ORANGE_SCORE` ,
`GREEN` ,
`GREEN_SCORE` ,
`NAME_TEAM`
)
VALUES (
'2014-07-28' , '1', '1', '1', '2', 'NAME_TEAM'
);
***/
$host = "localhost";
$name = "user";
$db = "db";
$password ="password";
function confirm_query($watever){
global $connection;
if (!$watever) {
die("Database query failed! " . mysqli_error($connection));
}
}
function select_query(){
global $connection;
$query = "SELECT * FROM `24992408` ";
$admin_set = mysqli_query($connection, $query);
confirm_query($admin_set);
return $admin_set;
}
$connection = mysqli_connect($host, $name, $password, $db);
$row = mysqli_fetch_assoc($admin_set = select_query());
$dateArray = explode('-', $row['THE_DATE']);
$year = $dateArray[0]; //echo $year; //2014
$month = $dateArray[1] - 1; //echo $month; //6
$day = $dateArray[2]; //echo $day; //28
// IN PUT
//$date1 = Date('Ymd',strtotime(sprintf('%04d%02d%02d',$year, $month, $day) ) ); //case 1
$date1 = "new Date ($year, $month, $day)"; //case 2
$dataArray[] = "[$date1, {$row['ORANGE']}, {$row['GREEN']}, '{$row['NAME_TEAM']}']";
$itemOutput[] = array( $date1, $row['ORANGE_SCORE'], $row['GREEN_SCORE'], $row['NAME_TEAM'] );
echo "data.addRows(" . json_encode($dataArray) . ");" ;
// OUT PUT
//data.addRows(["[20140628, 1, 2, 'NAME_TEAM']"]); // case 1 output
//data.addRows(["[new Date (2014, 6, 28), 1, 2, 'NAME_TEAM']"]); // case 2 output
?>
Related
i looping 2 array a date and the data
$rdate = $request->month; //<-- Requested month
$days = Carbon::create();
$days = $days->daysInMonth; //<-- Finding how much days in month
for ($i = 1; $i < $days; $i++) { //Looping Date
$date = $rdate . '-' . $i; //Making full Date with formate 'Y-m-d'
foreach ($games as $game) { //Looping game array have 3 collection ['game1', 'game2', 'game3']
$result = Result::whereDate('created_at', $date)->where('game', $game->name)->where('admin_id', $admin->id)->first(); // Query Results for getting perticular game with date
if ($result) { //Checking if current date haven't result
$r[] = [
'game' => $game->name,
'number' => $result->number
];
} else {
$r[] = [
'game' => $game->name,
'number' => '-'
];
}
}
$resultd[] = [
'date' => $date,
'results' => $r // i want to stop adding old data here
];
}
i am expecting this result
{"results":[{"date":"2020-08-1","results":[{"game":"game1","number":"-"},{"game":"game2","number":"-"},{"game":"game3","number":"-"}]},{"date":"2020-08-2","results":[{"game":"game1","number":"-"},{"game":"game2","number":"-"},{"game":"game3","number":"-"}]
What actually getting
Adding old $r to results array
How to fix it i am trying to break it but can't figure it out
I have some untested code, as I do not have your data but I think this code below should work, you may need to modify some code as needed.
$rdate = '2020-8';
$days = collect([1,2,3]);
$games = collect(['game1', 'game2', 'game3']);
return $days->map(function ($item) use ($rdate,$games) {
$date = $rdate.'-'.$item;
return [
"date" => $date,
"results" => $games->map(function ($g) use ($date) {
$result = Result::whereDate('created_at', $date)
->where('game', $g->name)
->where('admin_id', $admin->id)
->first();
return ['game' => $g->name,
'number' => $result ? $result->number : '-',
];
})
];
});
I'm building a class-schedule tool, where users can upload a .csv-file. I want to keep track of the dates with a variable so users can upload a schedule, which starts on the 15th of a month, for example. Therefore, I would like to increment a variable on date change. The data I receive from the csv looks like this:
array(
array(
'1',
'2019-10-15',
'Orientation / Team Building',
'371',
'',
'0',
'',
),
array(
'1',
'2019-10-16',
'Study Skills',
'371',
'',
'0',
'',
),
);
I would like to output one day at a time:
$currentMonth = date('F');
$dayOfSchedule = 0;
while ($dayOfSchedule < sizeof($schedule[$currentMonth]){
echo $schedule[$currentMonth][$dayOfSchedule][2]; //output the class etc.
}
and then increment $dayOfSchedule on the day change, but I don't know how to do that.
Any help is much appreciated!
You're probably looking for something like this:
<?php
$data = array(
array(
1,
'2019-10-16',
'Study Skills',
'371',
'',
0,
'',
),
array(
1,
'2019-10-16',
'Mathematics',
'371',
'',
0,
'',
),
array(
1,
'2019-10-15',
'Orientation / Team Building',
371,
'',
0,
'',
),
);
// map rows according to the date
$schedule = array_reduce($data, function ($accu, $row) {
$date = \DateTime::createFromFormat('Y-m-d', $row[1]);
$accu[$date->format('F')][$date->format('j')][] = $row;
return $accu;
}, []);
// sort the days and months
ksort($schedule);
array_walk($schedule, function (&$month_schedule) {
ksort($month_schedule);
});
$today = date('j'); // day of month today
if (isset($schedule[date('F')])) {
foreach ($schedule[date('F')] as $day => $rows) {
if ((int) $day >= (int) $today) {
echo " Day of Month: $day\n";
foreach ($rows as $key => $row) {
echo " Class({$key}): {$row[2]}\n";
}
}
}
echo "\n";
}
I'm trying to create Google Timeline chart using PHP & MySQL but without any success so far. So after endless hours of trying I've manage this so far:
First, I tried to create json using PHP (I believe that I've missed something here)
PHP
try {
$db = connectPDO();
$result = $db->query("SELECT naziv_plan AS name,
objava_odluke AS start_date,
datum_stupanja_glasnika AS end_date
FROM ispu_plan
WHERE datum_donosenja_plana
BETWEEN '2014-01-01'
AND CURDATE()
ORDER BY datum_donosenja_plana ASC");
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Godina', 'type' => 'string'),
array('label' => 'Odluka', 'type' => 'number'),
array('label' => 'glasnik', 'type' => 'number')
);
foreach($result as $r) {
$temp = array();
$temp[] = array('v' => (string) $r['naziv_plan']);
$temp[] = array('v' => (int) $r['objava_odluke']);
$temp[] = array('v' => (int) $r['datum_stupanja_glasnika']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table,JSON_NUMERIC_CHECK);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Using this block of code, I get this JSON (and it's valid, checked with JSONLint) But, I detected some unusual formatting and even after JSON_NUMERIC_CHECK
{"cols":[{"label":"Godina","type":"string"},{"label":"Odluka","type":"number"},{"label":"glasnik","type":"number"}],"rows":[{"c":[{"v":"Stambenog susjedstva - Stubi\u010dki Trnac - I.ID"},{"v":2014},{"v":2014}]},{"c":[{"v":"Prostorni plan ure\u0111enja Grada Krapine - IV. ID"},{"v":2013},{"v":2015}]},{"c":[{"v":"Prostorni plan ure\u0111enja Grada Donja Stubica - I ID"},{"v":2014},{"v":2015}]},{"c":[{"v":"Generalni urbanisti\u010dki plan Grada Krapine - V.ID"},{"v":2015},{"v":2016}]}]}
And here is JS:
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
var data = new google.visualization.DataTable(<?php echo $jsonTable;?>);
chart.draw(data);
After running this whole block of code, I get this error
Cannot read property 'v' of undefined
Is there something wrong with PHP code?
1.Maybe there is problem with date formatting?
Why do I get some weirdly formatted JSON Example -- *Stambenog susjedstva - Stubi\u010dki Trnac - I.ID when I should be getting instead of this ->Stubi\u010dki this-> Stubički
When I run SQL i get something like this (example below:)
+-----------+------------------+-----------------+
| name| | start_date | end_Date |
+-----------+------------------+-----------------+
| example_1 | 2014-06-06 | 2014-12-27 |
| example_1 | 2013-12-31 | 2015-06-07 |
| example_1 | 2016-06-06 | 2015-12-31 |
+-----------+------------------+-----------------+
*
I want to get something like this:
https://jsfiddle.net/api/post/library/pure/
UPDATE 1
So, I've managed to fix some of the addressed issues:
First, problem with weirdly formatted JSON, fixed with JSON_UNESCAPED_UNICODE
So, instead of this code:
$jsonTable = json_encode($table,JSON_NUMERIC_CHECK);
I used this :
$jsonTable = json_encode($table,JSON_UNESCAPED_UNICODE);
On the timeline note I've managed to successfully render timeline chart,but on x axis, instead of years and date it shows me hours.I believe that i've missed something when transforming from query to json.
(as seen in picture below)
I used this block of PHP code:
try {
$db = connectPDO();
$result = $db->query("SELECT naziv_plan, objava_odluke, datum_stupanja_glasnika
FROM ispu_plan
WHERE datum_donosenja_plana
BETWEEN '2014-01-01'
AND CURDATE()
ORDER BY datum_donosenja_plana ASC");
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Naziv plana', 'type' => 'string'),
array('label' => 'Odluka', 'type' => 'datetime'),
array('label' => 'glasnik', 'type' => 'datetime')
);
foreach($result as $r) {
$temp = array();
$temp[] = array('v' => (string) $r['naziv_plan']);
$temp[] = array('v' => (int) strtotime($r['objava_odluke']));
$temp[] = array('v' => (int) strtotime($r['datum_stupanja_glasnika']));
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table,JSON_UNESCAPED_UNICODE);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
And in JSON i get something like this 1402005600 for start date and in my table is formated like this 2014-06-06 and i believe that i need to get something like this 2014, 6, 6 to properly render and calculate timeline chart.
Please help with my lifetime crisis :)
UPDATE 2
Using whitehat knowledge and directions I'm feeling it that I'm one step closer to finally render this abomination :) Meanwhile, using directions and code that WhiteHat provided i created this:
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Godina', 'type' => 'string'),
array('label' => 'Odluka', 'type' => 'date'),
array('label' => 'glasnik', 'type' => 'date')
);
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$date1 = new DateTime();
$date2 = "Date(".date_format($date1, 'Y').", ".((int) date_format($date1, 'm') - 1).", ".date_format($date1, 'd').")";
$temp = array();
$temp[] = array('v' => (string) $row['naziv_plan']);
$temp[] = array('v' => (string) $date2);
$temp[] = array('v' => (string) $date2);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table,JSON_NUMERIC_CHECK);
Output of json is this:
{"cols":[{"label":"Godina","type":"string"},{"label":"Odluka","type":"date"},{"label":"glasnik","type":"date"}],"rows":[{"c":[{"v":"Stambenog susjedstva - Stubi\u010dki Trnac - I.ID"},{"v":"Date(2016, 8, 30)"},{"v":"Date(2016, 8, 30)"}]},{"c":[{"v":"Prostorni plan ure\u0111enja Grada Krapine - IV. ID"},{"v":"Date(2016, 8, 30)"},{"v":"Date(2016, 8, 30)"}]},{"c":[{"v":"Prostorni plan ure\u0111enja Grada Donja Stubica - I ID"},{"v":"Date(2016, 8, 30)"},{"v":"Date(2016, 8, 30)"}]},{"c":[{"v":"Generalni urbanisti\u010dki plan Grada Krapine - V.ID"},{"v":"Date(2016, 8, 30)"},{"v":"Date(2016, 8, 30)"}]}]}
And i get timeline, but without lines :(
Something like this:
And this two errors:
Expected number, "MNaN,0LNaN,40.992
Error: attribute x: Expected length, "NaN"
UPDATE 3
Ok, I believe that I've manage somehow, and it works. Here is code below, hope it helps someone. Once again thank you WhiteHat :)
try {
$db = connectPDO();
$result = $db->query("SELECT naziv_plan, objava_odluke, datum_stupanja_glasnika
FROM ispu_plan
WHERE datum_donosenja_plana
BETWEEN '2014-01-01'
AND CURDATE()
ORDER BY datum_donosenja_plana ASC ");
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Godina', 'type' => 'string'),
array('label' => 'Odluka', 'type' => 'date'),
array('label' => 'glasnik', 'type' => 'date')
);
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
// here I added rows in DateTime function, that was missing
$date1 = new DateTime($row['objava_odluke']);
$date2 = "Date(".date_format($date1, 'Y').", ".((int) date_format($date1, 'm') - 1).", ".date_format($date1, 'd').")";
$date3 = new DateTime($row['datum_stupanja_glasnika']);
$date4 = "Date(".date_format($date3, 'Y').", ".((int) date_format($date3, 'm') - 1).", ".date_format($date3, 'd').")";
$temp = array();
$temp[] = array('v' => (string) $row['naziv_plan']);
$temp[] = array('v' => (string) $date2);
$temp[] = array('v' => (string) $date4);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table,JSON_NUMERIC_CHECK);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
Picture, to prove it:
I have startdate and end date in my table like below.
startdate = 2016-01-01
Enddate = 2016-06-20
Now i want to send email automatically before 1 month from end date.
everything is working fine...email is also sending..
But my problem is i want to send email to multiple users if there are 2 rows match in table with my conditions then email is gone to both the users.
But my code only send email to only single users..not all users.
I want email is gone to all users one by one.
public function certificateExpired()
{
$this->autoRender = False;
$this->loadModel('Certificate');
$data = $this->Certificate->find("all", array(
'recursive' => -1, // should be used with joins
'fields' => array('User.*', 'Certificate.*'),
'joins' => array(
array(
'table' => 'users',
'alias' => 'User',
'type' => 'LEFT',
'conditions' => array('User.id = Certificate.user_id')
)
),
'conditions' => array('Certificate.is_expirable' => 1,'Certificate.status' => 1)
));
foreach ($data as $row) {
$currentdate = date("Y-m-d");
$date = $row['Certificate']['end_date'];
$newdate = strtotime($date .' -1 months');
$enddate = date('Y-m-d', $newdate);
if ($currentdate >= $enddate) {
//For sending email
$data['email'] = $row['User']['email'];
$data['name'] = $row['User']['name'];
$data['document_name'] = $row['Certificate']['name'];
$data['templateid'] = 19;
$send_mail = $this->EmailFunctions->certificateExpiredTemplate($data);
if ($send_mail) {
$this->redirect(array('controller' => 'Dashboards', 'action' => 'shipperDashboard'));
}
}
}
}
foreach ($data as $row) {
$currentdate = date("Y-m-d");
$date = $row['Certificate']['end_date'];
$newdate = strtotime($date .' -1 months');
$enddate = date('Y-m-d', $newdate);
if ($currentdate >= $enddate) {
//For sending email
$data['email'] = $row['User']['email'];
$data['name'] = $row['User']['name'];
$data['document_name'] = $row['Certificate']['name'];
$data['templateid'] = 19;
$send_mail = $this->EmailFunctions->certificateExpiredTemplate($data);
}
}
$this->redirect(array('controller' => 'Dashboards', 'action' => 'shipperDashboard'));
Change the foreach loop as above.
I think I'm close to completing the passing of MySQL data to Google Charts through JSON/AJAX. I am able to output a JSON string in the correct format but it is not outputting any SQL data. I've searched everywhere for a solution with no results. Anyone see what is missing from the code?
JSON output
{"cols":[{"id":"","label":"projid","type":"string"},{"id":"","label":"hours","type":"number"}],"rows":[{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]}]}
PHP->JSON
<?php
// -----> Query MySQL and parse into JSON below. <------
// write your SQL query here (you may use parameters from $_GET or $_POST if you need them)
require_once ("Includes/session.php");
require_once ("Includes/simplecms-config.php");
require_once ("Includes/connectDB.php");
$recId = null;
$projid = null;
$hours = null;
$recId = $_GET['id'];
$projid = $_GET['projid'];
$hours = $_GET['hours'];
$query = "SELECT projid, hours FROM hours WHERE id = ?";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('d', $recId);
$statement->execute();
$results = $statement->get_result();
$rows = array();
$table = array();
$table['cols'] = array(
array('id' => "",'label' => 'projid', 'type' => 'string'),
array('id' => "",'label' => 'hours', 'type' => 'number')
);
/* Extract the information from $result */
while ($r = $results->fetch_assoc()) {
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['projid']);
// Values of each slice
$temp[] = array('v' => (int) $r['hours']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
echo $jsonTable;
?>
The following code returned the correct array for Google Charts. Google Charts - JSON Data
<?php
// -----> Query MySQL and parse into JSON below. <------
require_once ("Includes/connectDB.php");
$result = $databaseConnection->query("SELECT projid, hours FROM alloc_hours");
$table = array();
$table['cols'] = array(
array('id' => "", 'label' => 'projid', 'pattern' => "", 'type' => 'string'),
array('id' => "", 'label' => 'hours', 'pattern' => "", 'type' => 'number')
);
$rows = array();
while ($nt = $result->fetch_assoc())
{
$temp = array();
$temp[] = array('v' => $nt['projid'], 'f' =>NULL);
$temp[] = array('v' => $nt['hours'], 'f' =>NULL);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
Array
{"cols":[{"id":"","label":"projid","pattern":"","type":"string"},{"id":"","label":"hours","pattern":"","type":"number"}],"rows":[{"c":[{"v":"2","f":null},{"v":"8","f":null}]},{"c":[{"v":"1","f":null},{"v":"6","f":null}]},{"c":[{"v":"3","f":null},{"v":"20","f":null}]},{"c":[{"v":"2","f":null},{"v":"10","f":null}]},{"c":[{"v":"4","f":null},{"v":"5","f":null}]},{"c":[{"v":"1","f":null},{"v":"30","f":null}]}]}
Try replacing this line:
$statement->store_result();
with:
$results = $statement->get_result();
and replace the foreach loop with a while loop:
while ($r = $results->fetch_assoc()) {
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['projid']);
// Values of the each slice
$temp[] = array('v' => (int) $r['hours']);
$rows[] = array('c' => $temp);
}
That should get the query to return results. You don't need the lines:
$statement->bind_result($projid, $hours);
$statement->fetch();