PHP: Increment variable on date change - php

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";
}

Related

how to stop adding more data in array in foreach loop

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 : '-',
];
})
];
});

Lavachart display count each months

Hello i need serious help cause i have tried all way and not find an answer... so i really want to display chart that count many data each month, ex january 2 data, febuary 3 data etc... pls look at this brother
public function lihatkeluhan(){
$halaman="tindaklayanan";
$keluhan_list=DB::table('keluhans')
->select(DB::raw('id,tanggal,produk,username,area,masalah,status'))->get();
$keluhan_group = keluhan::select(DB::raw('id,tanggal,produk,username,area,masalah,status'))
->get()->groupBy(function($date) {
return Carbon::parse($date->tanggal)->format('m'); // grouping by months
});
foreach ($keluhan_group as $group) {
$count[] = count($group);
}
$bulan = array("Jan","Feb","Mar","Apr","Mei","Jun","Jul","Agu","Sep","Okt","Nov","Des");
$count = Count($keluhan_list);
$population = Lava::DataTable();
$population->addDateColumn("Month")
->addNumberColumn('Keluhan');
foreach($keluhan_group as $group){
$population->addRow(["jan",$count]);
}
Lava::LineChart('Population', $population, [
'title' => 'Tahun : 2017',
'titleTextStyle' => [
'color' => '#212F3C',
'fontSize' => 14
]
]);
$keluhan_group used to group by month
$count result is number of data each month
But idk how to display on chart...
Btw $population->addDateColumn("Month") is not work, it not display month but year T_T
Replace your code from $keluhan_group to $population with below code and check.
here you need to pass array of month and count of that month
$keluhan_group = keluhan::select(DB::raw("COUNT(*) as count , MONTHNAME(created_at) as month"))
->orderBy("created_at")
->groupBy(DB::raw("month(created_at)"))
->get()->toArray();
$chart_array = array();
foreach($keluhan_group as $data){
$n_data = [];
array_push($n_data,$data['month'],$data['count']);
array_push($chart_array,$n_data);
}
$population = Lava::DataTable();
$population->addDateColumn("Month")
->addNumberColumn('Keluhan')
->addRow($chart_array);
hope this will Help.
see i have implemented chart using my 'User' tabel,
i was not having lavachart in my project so i have update it using http://itsolutionstuff.com/post/laravel-5-geo-chart-example-and-demo-using-lavacharts-packageexample.html
here is my controller code:
$users = Users::select(DB::raw("COUNT(*) as count , MONTHNAME(created_at) as month"))
->orderBy("created_at")
->groupBy(DB::raw("month(created_at)"))
->get()->toArray();
$chart_array = array();
foreach($users as $data){
$n_data = [];
array_push($n_data,$data['month'],$data['count']);
array_push($chart_array,$n_data);
}
$lava = new Lavacharts;
$popularity = $lava->DataTable();
$popularity->addStringColumn('Country')
->addNumberColumn('Popularity')
->addRows($chart_array);
$lava->LineChart('demochart', $popularity, [
'title' => 'Demo population count',
'animation' => [
'startup' => true,
'easing' => 'inAndOut'
],
'colors' => ['blue', '#F4C1D8']
]);
return view('welcome', ['lava' => $lava]);
and in my .blade file:
<div id="temps_div"></div>
<?= $lava->render('LineChart', 'demochart' , 'temps_div') ?>
Hope this will Help.
$companies=Company::all();
$start = (new DateTime('2017-01-01'))->modify('first day of this month');
$end = (new DateTime('2022-01-01'))->modify('first day of next month');
$interval = DateInterval::createFromDateString('12 month');
$period = new DatePeriod($start, $interval, $end);
$lava = new Lavacharts; // See note below for Laravel
$finances = \Lava::DataTable();
$finances->addDateColumn('Year');
foreach($companies as $company)
{
$finances ->addNumberColumn($company->company_name." ".$company->company_location." total sales amount");
}
foreach ($period as $dt) {
$yeardate=$dt->format("Y-m-d");
$insertrow = array( $yeardate );
foreach($companies as $company)
{
$cmp= $company->company_name;
$loc= $company->company_location;
$companiesinfo[]=$cmp." ".$loc;
$databasename=$company->database_name;
\Config::set('database.connections.tenant.host', 'localhost');
\Config::set('database.connections.tenant.username','root');
\Config::set('database.connections.tenant.password', '');
\Config::set('database.connections.tenant.database', $databasename);
\Config::set('database.default', 'tenant');
DB::reconnect('tenant');
$calculatesalesofcompany=B2CFINAL::
select(DB::raw('sum(GrandTotal) as total'))
->where(DB::raw('YEAR(SaleDate)'), '=', $yeardate)
->first();
if($calculatesalesofcompany->total==null)
{
$calculatesalesofcompany->total=0;
}
array_push( $insertrow, $calculatesalesofcompany->total );
}
$finances ->addRow($insertrow);
}
\Lava::ComboChart('Finances2', $finances2, [
'title' => 'Company Performance',
'titleTextStyle' => [
'color' => 'rgb(123, 65, 89)',
'fontSize' => 16
],
'legend' => [
'position' => 'in'
],
'seriesType' => 'bars',
]);

new Date into Array php

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
?>

codeigniter mysql stop third consecutive insert

I have this codeigniter mysql code to create an appointment:
if ($this->form_validation->run() == TRUE)
{
$data = array(
'startTime' => $startTime ,
'endTime' => $endTime ,
'day' => $date ,
'contact_id' => $this->input->post('InputPatient')
);
$this->db->insert('rdv', $data);
echo 'Appointment Created Successfully.';
}
What I need is - for a specific time like 8pm, I should not have more than 2 appointment created. On third insert with same start time, I should give an error.
Thanks.
Before you do your insert you could do a select to see how many entries there are with the same start time. If there are less than 2 then you can proceed to do your insert.
$this->db->select('count(*) as count')
->from('rdv')
->where('startTime', $startTime)
->where('day', $date);
$query = $this->db->get();
$aResult = $query->row_array();
if($aResult['count'] < 2)
{
//Do your insert
}
Here you go. Before you insert, check if there are already 2 appointments for a specific time and date.
if ($this->form_validation->run() == TRUE)
{
$data = array(
'startTime' => $startTime ,
'endTime' => $endTime ,
'day' => $date ,
'contact_id' => $this->input->post('InputPatient')
);
$isAlreadyTwo = $this->db->from("rdv")
->where(array("startTime" => $startTime, "day" => $day))
->count_all_results() >= 2;
if($isAlreadyTwo)
{
echo "Error!!";
}
else
{
$this->db->insert('rdv', $data);
echo 'Appointment Created Successfully.';
}
}
Hope this helps :)

Logo change with date script

I just wondered if anybody can point me in the right direction: I'm looking to make a script whereby the logo on my site changes depending on the date; so for instance a haloween style one soon.
I started off by having 2 arrays, 1 of start dates and 1 of end dates(not sure even if this is the best way!):
<?php
$start_dates = array('01/01' => 'New Years',
'14/02' => 'Valentine Day',
'16/02/2010' => 'Pancake Day',
'17/03' => 'St Patricks Day',
'01/04' => 'April Fools',
'02/04/2010' => 'Easter',
'23/04' => 'St Georges Day',
'11/06/2010' => 'World Cup',
'31/10' => 'Halloween',
'05/11' => 'Guy Fawkes',
'11/11' => 'Armistice Day',
'16/10' => 'Today',
'15/12' => 'Christmas');
$end_dates = array( '08/01' => 'New Years',
'15/02' => 'Valentine Day',
'17/02/2010' => 'Pancake Day',
'18/03' => 'St Patricks Day',
'02/04' => 'April Fools',
'06/04/2010' => 'Easter',
'24/04' => 'St Georges Day',
'12/07/2010' => 'World Cup',
'01/11' => 'Halloween',
'06/11' => 'Guy Fawkes',
'12/11' => 'Armistice Day',
'17/10' => 'Today',
'01/01' => 'Christmas');
?>
Easy so far...the problemis that I need a way of working out if todays date falls between the start date and end date, then changing the image file name.
Its a long shot but I hope someone would be kind enough to help.
Thanks,
B.
like this
$events = array(
'New Year' => '01/01 01/08',
'Pancake Day' => '16/02/2010 17/02/2010',
//etc
);
echo find_event($events, '16/02');
where find_event() is
function mdy2time($date) {
$e = explode('/', $date);
if(count($e) < 3)
$e[] = '2010';
return strtotime("$e[1]-$e[0]-$e[2]");
}
function find_event($events, $date = null) {
$date = is_null($date) ? time() : mdy2time($date);
foreach($events as $name => $range) {
list($start, $end) = explode(' ', $range);
if($date >= mdy2time($start) && $date <= mdy2time($end))
return $name;
}
return null;
}
you should use an array more like this:
$dates = array();
$dates[] = array(
'name' => 'New Years'
'start' = '01/14',
'end' => '01/20',
'style' => 'haloween',
);
$dates[] = array(
//...
);
then you can get the style as follows:
$style='default';
// date as number e.g. 130 (january 30th)
$currDate = date('md',time()) * 1;
foreach ($dates AS $k => $v) {
$tmp = explode("/",$v['start'];
$start = ($tmp[1].$tmp[0])*1;
$tmp = explode("/",$v['end'];
$stop = ($tmp[1].$tmp[0])*1;
if ($start <= $currDate && $currDate < $stop) {
$style=$v['style'];
break;
}
}
echo 'style: '.$style;
Didn't check the code yet, so feel free to correct me if iam wrong.

Categories