I'm doing a school project and I have to create a schedule from an array. I already sorted the array by day & time. I know how to create a simple table and insert the data - but I wanted to make a more defined table in relation to time:
The array for Monday looks like this:
Array ( [0] => Array ( [courseID] => comp275 [lectureID] => gg [day] => monday [stime] => 12:15 [etime] => 15:16 [term] => winter [year] => 2014 ) [1] => Array ( [courseID] => comp345 [lectureID] => ss [day] => monday [stime] => 18:20 [etime] => 20:30 [term] => winter [year] => 2014 ) )
I want the table to be like this for column "Monday"
table type http://4.ii.gl/mtHVQN.png
This is my code at the moment (its a bit broken but i haven't figured out how to do what i really want yet.)
<table>
<tr>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
</tr>
<?php getMonday($Array); ?>
</table>
Function :
foreach($Array as $MA)
{
echo
"<tr class='success'><td>".
"Start-Time :".$MA["stime"]." "
."<br><br>".
"Course :".$MA["courseID"]." "
."<br><br>".
"End-Time :".$MA["etime"]." "
."</td></tr>";
}
Gives me this :
table type2 http://2.ii.gl/Q1Dx-x.png
Instead of using cells in your day colum, you could create divs for each class and change the height based off the time. For example -
$curr_time = strtotime('08:00'); //beginning of the day
foreach($Array as $MA) {
// create a blank div if it does not equal $curr_time
if(strtotime($MA['stime']) != $curr_time){
$empty_size = // get size for difference between $MA['stime'] and $curr_time
echo "<div style='height:{$empty_size}px;'></div>";
}
// create the div for the class time
$div_size = // get size for difference between $MA['etime'] and $MA['stime']
echo "<div class='success' style='height:{$div_size}px;'>".
// your data
"Start-Time :".$MA["stime"]." "
."<br><br>".
"Course :".$MA["courseID"]." "
."<br><br>".
"End-Time :".$MA["etime"].
// end of your data
"</div>";
// change the $curr_time to $MA['etime']
$curr_time = strtotime($MA['etime']) ;
}
since this is a school project, I won't give you all the code / full working example, just this sample code/idea. You would need to find a way to determine the height of the divs based off the difference in time. Hopefully this helps.
Related
I have an input array which contains arrays of day and time data:
$temp = Array
(
[0] => Array
(
[day] => Tuesday
[time] => 07:44 pm - 08:44 pm
)
[1] => Array
(
[day] => Tuesday
[time] => 04:00 am - 04:25 am
)
[2] => Array
(
[day] => Sunday
[time] => 04:00 am - 04:25 am
)
[3] => Array
(
[day] => Sunday
[time] => 04:00 am - 04:25 am
)
[4] => Array
(
[day] => Friday
[time] => 04:00 am - 04:25 am
)
[5] => Array
(
[day] => Friday
[time] => 04:00 am - 04:25 am
)
)
Now I want to group the common times display as one element and if the time is the same for more than one day then it's should display one entry. So what is the best way to achieve the desired result without making this too complex?
Array
(
[0] => Array
(
[day] => Tuesday
[time] => 04:00 am - 04:25 am & 07:44 pm - 08:44 pm
)
[1] => Array
(
[day] => Friday & Sunday
[time] => 04:00 am - 04:25 am
)
)
Here it's what I have done:
$final = [];
foreach ($temp as $val) {
$final[strtolower($val['day'])][] = $val['time'];
}
foreach ($final as $k => $v) {
sort($v);
$v = array_unique($v);
$last = array_pop($v);
$final[$k] = [
'day' => $k,
'time' => count($v) ? implode(", ", $v) . " & " . $last : $last,
];
}
There are 4 basic steps:
Remove duplicate rows.
Sort all rows by day (via lookup) ASC, then time (as a string) ASC.
Store joined time values using day values as temporary keys.
Store joined day values using joined time values as temporary keys.
Code: (Demo)
$array=[
['day'=>'Tuesday','time'=>'07:44 pm - 08:44 pm'],
['day'=>'Tuesday','time'=>'04:00 am - 04:25 am'],
['day'=>'Sunday','time'=>'04:00 am - 04:25 am'],
['day'=>'Sunday','time'=>'04:00 am - 04:25 am'],
['day'=>'Friday','time'=>'04:00 am - 04:25 am'],
['day'=>'Friday','time'=>'04:00 am - 04:25 am']
];
$array=array_unique($array,SORT_REGULAR); // remove exact duplicate rows
$order=array_flip(['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']); // lookup array
usort($array,function($a,$b)use($order){ // sort by day name ASC then time ASC
if($order[$a['day']]==$order[$b['day']]){
return $a['time']<=>$b['time']; // 2nd sort criteria: time string
}
return $order[$a['day']]<=>$order[$b['day']]; // 1st sort criteria: day name via lookup array
});
foreach($array as $row){
if(!isset($temp[$row['day']])){
$temp[$row['day']]=$row['time']; // store time for first occurring day
}else{
$temp[$row['day']].=" & {$row['time']}"; // join times (for pre-existing day) as they are found
}
}
foreach($temp as $day=>$times){
if(!isset($result[$times])){
$result[$times]=['day'=>$day,'time'=>$times]; // store first occurring day and time using time as temp key
}else{
$result[$times]['day'].=" & $day"; // join day names as they are found
}
}
var_export(array_values($result)); // optionally remove the temporary keys
Output:
array (
0 =>
array (
'day' => 'Tuesday',
'time' => '04:00 am - 04:25 am & 07:44 pm - 08:44 pm',
),
1 =>
array (
'day' => 'Friday & Sunday',
'time' => '04:00 am - 04:25 am',
),
)
Here is another version that doesn't call array_unique(), but I don't like it as much because it does iterated sort() calls and generates a deeper temporary array.
foreach($array as $row){
$temp[$row['day']][$row['time']]=$row['time']; // remove duplicates and group by day
}
$order=array_flip(['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']); // lookup array
uksort($temp,function($a,$b)use($order){
return $order[$a]<=>$order[$b]; // sort by day name via lookup array
});
foreach($temp as $day=>$times){
sort($times); // sort time elements ASC
$time_key=implode(' & ',$times); // join the day's time elements
if(!isset($result[$time_key])){ // if first occurrence of the time string
$result[$time_key]=['day'=>$day,'time'=>$time_key]; // store data using time string as temp key
}else{
$result[$time_key]['day'].=" & {$day}"; // concatenate new day to day element
}
}
var_export(array_values($result));
I am desperate because of my lack of programming experience.
I am working on a small WordPress plugin, a room booking system.
Now my problem is to create the daily overview.
In the database, there is a table with all bookings looking like this:
--------------------------------------------------------------
|id|user_id| starttime | endtime |room|type|
---+-------+-------------------+-------------------+----+-----
|1 | 101|2017-08-24 11:00:00|2017-08-24 12:30:00|12 | 4 |
|2 | ...
The overview / calendar / schedule for every day should be made as an HTML-Table using Bootstrap and look like the following:
Time Conference Room Meeting Room Lobby
07:00 Mr. T
08:00 Mr. T
09:00 C.J.P. Mrs. L.
10:00
11:00
12:00 Mrs. M
So the free timeslots should be empty columns.
To achieve this, I started using a function to create all starttimes:
$times_array = array();
$timing_interval = get_option('timing');
for ($hours = get_option('starttime'); $hours < get_option('endtime'); $hours++) {
for ($m = 0; $m < 60; $m += $timing_interval) {
$starttime_html = sprintf('%02u:%02u', $hours, $m);
$times_array[$starttime_html]='';
}
}
Afterwards I created an array containing the already saved bookings:
$booking_array = array();
$statement = $wpdb->get_results( $wpdb->prepare("SELECT {$mpbs_prefix}_bookings.id, user_id, wp_users.user_nicename AS username_nice, starttime, facility_id, roomname, equipment_1, {$mpbs_prefix}_equipment.name AS eq_1_name, equipment_2 FROM {$mpbs_prefix}_bookings, {$mpbs_prefix}_facilities, {$mpbs_prefix}_equipment, wp_users WHERE user_id = wp_users.ID AND equipment_1 = {$mpbs_prefix}_equipment.id AND {$mpbs_prefix}_facilities.id = {$mpbs_prefix}_bookings.facility_id AND starttime >= '2017-08-22 00:00:00'"),ARRAY_A);
$bookingrow = 0;
foreach($statement as $actualbookings) {
$starttime_currentday = explode(" ",$statement[$bookingrow]['starttime']);
$starttime_curr_hm = substr($starttime_currentday[1],0,5);
$booking_array[$bookingrow] =
array('starttime_of_booking'=>$starttime_curr_hm, 'facliId'=>$statement[$bookingrow]['facility_id'],'userid'=> $statement[$bookingrow]['username_nice'], 'horse_1_name' => $statement[$bookingrow]['horse_1_name']);
$bookingrow++;
}
As there are a lot of rooms (facilities) in different categories, I chose a tabbed navigation from Bootstrap.
Therefore I created a function to "draw" the table using information from three directions:
The column heads directly from the database
the starting times created in PHP (see above)
the already booked times and facilities saved in my $booking_array
As the HTML-table is created row wise, I thought it would be a good approach to check if the starttime is also available in the $booking_array and if yes to add a cell containing the username.
So far that worked, but now I wanted to have all free slots as empty cells. So I tried a lot but always end up in a table with hundreds of empty rows.
In my last approach I used a function I found here, to check if the starttime is not in my multidimensional associative array ($booking_array) and to add the empty cell:
$drawTable = function($funcFormCat, $funcFacId) use ($mpbs_overview_category_query, $times_array, $booking_array) {
echo "<table class='table table-hover'>";
echo "<thead>";
//echo "<th class='text-center'></th>";
foreach ($mpbs_overview_category_query as $overview_formcategories) {
if ($overview_formcategories->formcategory == $funcFormCat && $overview_formcategories->facility_id == $funcFacId) {
echo "<th class='text-center' id='$overview_formcategories->facility_id'>" . $overview_formcategories->facility ."</th>";
}
}
echo "</thead>";
foreach ($times_array as $timeskey => $timesvalue) {
echo "<tr>";
// echo "<td class='text-center'>.</td>";
for ($booking_array_id = 0; $booking_array_id < count($booking_array); $booking_array_id++ ) {
if ($booking_array[$booking_array_id]['starttime_of_booking'] == $timeskey && $booking_array[$booking_array_id]['facliId'] == $funcFacId ) {
echo "<td class='text-center'>" . $booking_array[$booking_array_id]['username'] . "</td>";
echo "</tr>";
}
elseif (in_array_r($timeskey, $booking_array)==false) {
echo "<td class='text-center'>**</td>";
echo "</tr>";
}
}
}
My arrays do contain the following format:
$times_array
Array ( [07:00] => [07:30] => [08:00] => [08:30] => [09:00] => [09:30] => [10:00] => [10:30] => [11:00] => [11:30] => [12:00] => [12:30] => [13:00] => [13:30] => [14:00] => [14:30] => [15:00] => [15:30] => [16:00] => [16:30] => [17:00] => [17:30] => [18:00] => [18:30] => [19:00] => [19:30] => [20:00] => [20:30] => [21:00] => [21:30] => )
$booking_array
Array ( [0] => Array ( [starttime_of_booking] => 08:00 [facliId] => 6 [userid] => Mr T [equipment] => Beamer ) [1] => Array ( [starttime_of_booking] => 14:00 [facliId] => 4 [userid] => Mrs. L [equipment] => Flipchart ) [2] => Array ( [starttime_of_booking] => 14:00 [facliId] => 9 [userid] => Mrs. M [equipment] => TV-Set ) [3] => Array ( [starttime_of_booking] => 13:00 [facliId] => 8 [userid] => C.J.P. [equipment] => Stuff )
As I am trying around for hours now and do not get a correct overview, I would be very happy for any hints, tips or suggestions!
Thanks in advance.
Regards
Lars
To clarify, what I want to achieve, I add some more information here:
What I want is to create a HTML-Table, which is populated from the 3 sources:
At first he table's heading should be made by a SQL-query to get the room names and their ids. (<thead><th id='facility_id'>room1</th><th id='facility_id'>room2</th id='facility_id'>...</thead>
Afterwards in the 1st data row in the 1st column the 1st starttime coming from $times_array should be printed. ("<td>".$timeskey."</td>").
All remaining cells should also be formatted as HTML-Cells.
Now comes the tricky part (for me), as I want to populate those cells, where already a booking was made.
For example the conference room is booked from 07:00 to 09:00 by Mr.T.
To achieve this without Ajax, I created the array $booking_array with the data from my bookings database table.
Now I am stuck on writing a function, which draws my HTML-Table with all necessary information at the right place.
A <tr> tag is printed to open a new row. In the next step a cell with the starttime is added. And now I want to iterate through my $bookings_array for any booking starting at this time and printing the username to the corresponding column.
As I did not get that to work, in one table, I tried to achieve it by creating a single table for each room containing the starttimes and the column with the booking data / free slots. But the table gets hundreds of rows.
I need to export a set of json data for highchart. But I'm having a problem with looping.
I've got 2 set of arrays:
Years Array (2015,2014,2013,2012) - form MySQL
Month Array (01,02,03,04,05,06,07,08,09,10,11,12)
So I make it in array - multidimensional. With this code.
$sql_arrYr=mysqli_query($con,"select year(bk_date1) as arrYr from booking_db group by year(bk_date1) order by arrYr asc");
while($rec_arrYr=mysqli_fetch_array($sql_arrYr)){
$arrYr[$rec_arrYr['arrYr']]=array("01","02","03","04","05","06","07","08","09","10","11","12");
}
Then I've got:
Array ( [2015] => Array ( [0] => 01 [1] => 02 [2] => 03 [3] => 04 [4] => 05 [5] => 06 [6] => 07 [7] => 08 [8] => 09 [9] => 10 [10] => 11 [11] => 12 )...);
Which is looking good coz I have all data I need in a set of arrays - year and each month values.
So I continue with fetching data from mySQL with this code.
foreach($arrYr as $key=>$val){
$rows=array();
$rows[type]='spline';
$rows[name]=$key;
foreach($val as $mon){
$sql_nBk=mysqli_query($con,"select count(*) as nBkr from booking_db where year(bk_date1)='$key' and month(bk_date1)='$mon'");
$rec_nBk=mysqli_fetch_array($sql_nBk);
$rows[data][]=$rec_nBk['nBkr'];
}
}
echo json_encode($rows);
The problem happened here. It's not loop. The only line I've got is.
{"type":"spline","name":2015,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
Which I expect this:
{"type":"spline","name":2015,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
{"type":"spline","name":2014,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
{"type":"spline","name":2013,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
{"type":"spline","name":2012,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
Please give me a reason why it's not loop. Even I put them in a right loop.
You are setting $rows to an empty array each time through the outer loop. Also, you can't have duplicate keys. The first type is overwritten by the next (also name and data) so you have to make it multidimensional. You can use the $key variable for this to make it easy, or implement a counter $i and use $i++ or something.
$i = 0;
foreach($arrYr as $key=>$val){
$rows[$i]['type']='spline';
$rows[$i]['name']=$key;
foreach($val as $mon){
$sql_nBk=mysqli_query($con,"select count(*) as nBkr from booking_db where year(bk_date1)='$key' and month(bk_date1)='$mon'");
$rec_nBk=mysqli_fetch_array($sql_nBk);
$rows[$i]['data'][]=$rec_nBk['nBkr'];
}
$i++;
}
echo json_encode($rows);
I am trying to code a cron job so if a code in the database and is unused and older then 72 hours it drops the row in the database.
The problem I am having however is that when I am trying to get the array data in a row, so I can run an 'If statement' and then the drop command, when printing the array I get duplicates like as follows
33520891520891do not usedo not use----aaron hattonaaron hattonSunday 8th of September 2013 12:46:20 PMSunday 8th of September 2013 12:46:20 PMUnusedUnused--
My code is as follows
// Set variable for the time
$timenow = date('l jS \of F Y h:i:s A');
// Start Expired password check and drop function
function cronexec_expired ($timenow) {
include('../../config.php');
// Open up a new MySQLi connection to the MySQL database
mysql_connect($dbHost, $dbUsername, $dbPassword);
mysql_select_db($dbTable);
// Query to check the status of the code input
$expiry_check = "SELECT * FROM code_log WHERE status='Unused'";
// Run the query
$expiry_checkexec = mysql_query($expiry_check);
while($expiry_possibles = mysql_fetch_array($expiry_checkexec)) {
foreach ($expiry_possibles as $expiry_possible) {
print_r ($expiry_possible);
};
}
}
// Start Redeemed Password check and drop function
// Execute Functions
cronexec_expired ($timenow);
Any help would be really appreciated!
Edit
When removing the 'foreach' and running the following:
print_r ($expiry_possibles);
I get the following
Array ( [0] => 3 [id] => 3 [1] => 520891 [code] => 520891 [2] => do not use [refid] => do not use [3] => - [hostname] => - [4] => - [userip] => - [5] => aaron hatton [creater] => aaron hatton [6] => Sunday 8th of September 2013 12:46:20 PM [timecreated] => Sunday 8th of September 2013 12:46:20 PM [7] => Unused [status] => Unused [8] => - [timeredeemed] => - )
Am I doing something wrong?
if you mean numeric index in your array output. use mysql_fetch_assoc() instead of mysql_fetch_array()
mysql_fetch_array() essentially returns two arrays one with numeric index, one with associative string index.
I have some date, like:
20 November 06:10
12 November 08:12
10 October 13:23
There all in the past 6 months, Now I want to strtotime() them, but they are all un complete (lack of year), how to make some process so that I could strtotime() them?
Try this:
$dates = array("10 October 13:23", "12 November 08:12", "10 October 13:23");
foreach($dates as $d){
$exploded = explode(" ", $d);
$newDate = array_slice($exploded, 0,2,true)+array(2=>"2012")+array(3 => $exploded[2]);
//print_r($newDate);
$time = strtotime(implode($newDate));
echo $time."<br/>";
}
The output i got is:
1349868180
1352704320
1349868180
The logic is:
You lack the year, so I exploded the dates into an array to slice them, insert the year (the +array(2=>"2012") part) and glue them again with implode, and then run the strtotime.
This work only for this year, so you can use this logic to add the year to all your dates, or in the future there will be absolutely no way to filter dates from different years.
I added the dates into an array for loop through all of them, you can use the loop other ways, depending on where you have all your dates stored. For example if they are in a database you can include the script in the while($row = mysqli_fetch_assoc($result)) part where $d would be $row['date'] instead.
You should use the DateTime class and its createFromFormat and getTimeStamp methods instead of strtotime.
print_r(date_parse_from_format("d F H:i", '20 November 06:10'));
gives you:
Array
(
[year] =>
[month] => 11
[day] => 20
[hour] => 6
[minute] => 10
[second] => 0
[fraction] =>
[warning_count] => 0
[warnings] => Array
(
)
[error_count] => 0
[errors] => Array
(
)
[is_localtime] =>
)