I have 2 time strings as below:
10pm
3am
I want to print the time between above-given string like:
10pm
11pm
12am
1am
2am
3am
PHP Code I tried:
<?php
$new_otime = strtotime(date('H:i',strtotime('10pm')));
$close_time = strtotime(date('H:i',strtotime("3am")));
do { ?>
<option value="<?php echo date("g a",$new_otime) ?>"><?php echo date("g a",$new_otime); ?></option>
<?php
$new_otime = $new_otime+=3600;
} while ($new_otime == $close_time);
?>
But it echoes only 10 pm in the select box. How can I echo all the time between those string?
I suggest some work around to make this work:
<?php
$new_otime = strtotime(date('Y-m-d H:i',strtotime(date('Y-m-d').' 10pm')));
$close_time = strtotime(date('Y-m-d H:i',strtotime(date('Y-m-d').' 3am')));
if($close_time < $new_otime){
$close_time = strtotime(date('Y-m-d H:i',strtotime(date('Y-m-d',strtotime('+1 day')).'3am')));
}
do { ?>
<option value="<?php echo date("g a",$new_otime) ?>"><?php echo date("g a",$new_otime); ?></option>
<?php
$new_otime = $new_otime+=3600;
} while ($new_otime <= $close_time);
?>
Check if end time is bigger
If not make it next day
Loop while new_otime is less than close_time
You could also try using DateTime and DatePeriod:
$from = date_create_from_format('ha', '10pm');
//create 5 interations, each adds an additional hour
$dp = new DatePeriod($from, new DateInterval('PT1H'), 5);
/** #var DateTime $d */
foreach ($dp as $d) {
echo $d->format('ha');
}
I hope this is what you are looking for:
$time=22;
for($i=0;$i<6;$i++) {
echo date("g a",mktime($time+$i,0,0,09,21,2016))."<br>";
}
Try this
$new_otime = "10pm";
$close_time = "3am";
$counter=0;
while(date("g a",strtotime($new_otime)+3600*$counter)<=date("g a",strtotime($close_time))){
echo date("g a",strtotime($new_otime)+3600*$counter).'<br>';
$counter++;
}
Try this code
<?php
$new_otime = "10pm";
$close_time = "3am";
$new_otime = strtotime(date_create_from_format("ha", $new_otime)->format("ha"));
$close_time = strtotime(date_create_from_format("ha", $close_time)->format("ha"));
do {
?>
<option value="<?php echo date("ha", $new_otime) ?>"><?php echo date("ha", $new_otime); ?></option>
<?php
$new_otime = strtotime(date("ha", strtotime("+1 hours", $new_otime)));
} while ($new_otime != $close_time);
if ($new_otime == $close_time) {
?>
<option value="<?php echo date("ha", $new_otime) ?>"><?php echo date("ha", $new_otime); ?></option>
<?php } ?>
Related
I'm trying to create a page where i can choose the hour to take a date with someone.
In my database i already have 3 dates for today as here :
at 9:00, 10:00 and 12:00 so these hours should not apear in the page.
But what i have is this :
9:30:00
9:30:00
10:00:00
10:30:00
11:00:00
11:00:00
11:00:00
11:30:00
11:30:00
11:30:00
12:00:00
12:00:00
14:00:00
14:00:00
14:00:00
...
I think there is an algorythm problem but i'm not shure there is the code :
<?php
/**
* Template Name: calendrier
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
//
get_header(); ?>
<div id="primary" <?php generate_do_element_classes( 'content' ); ?>>
<main id="main" <?php generate_do_element_classes( 'main' ); ?>>
<?php
do_action( 'generate_before_main_content' );
if(!isset($_GET['mydate'])){
$today=getdate();
$_GET['mydate']=$today['year']."-".$today['mon']."-".$today['mday'];
}
echo "<p>Entrez une date :</br><form action=\"\" method=\"get\"><input type=\"hidden\" name=\"page_id\" value=\"21\"><input type=\"hidden\" name=\"myuser\" value=\"".$_GET['myuser']."\" ><input type=\"hidden\" name=\"myform\" value=\"".$_GET['myform']."\"><input type=\"date\" name=\"mydate\" /></p><input type=\"submit\" value=\"Modifier la date\" /></form>";
$mydata = $wpdb->get_results(
$wpdb->prepare("
SELECT *
FROM cal
WHERE user_id = %s
AND date = %s
",
$_GET['myuser'],
$_GET['mydate']
)
);
$disp = $wpdb->get_results(
$wpdb->prepare("
SELECT * from disponibility where user_id = %s and date = %s
",
$_GET['myuser'],
$_GET['mydate']
)
);
$cat = $wpdb->get_row(
$wpdb->prepare("
SELECT * from cat where id = %s
",
$_GET['myform']
)
);
echo "<h1>Calendrier ".$_GET['mydate']."</h1>";
foreach($disp as $dispun){
$debut = $dispun->start; // start hour
$fin = $dispun->end; // end hour
$debut_parts = explode(":", $debut);
$fin_parts = explode(":", $fin);
$debut_parts[0] = intval($debut_parts[0]); // int start hour
$debut_parts[1] = intval($debut_parts[1]); // int start minutes
$debut_parts[2] = intval($debut_parts[2]); // int start seconds
$fin_parts[0] = intval($fin_parts[0]); // int end hour
$fin_parts[1] = intval($fin_parts[1]); // ...
$fin_parts[2] = intval($fin_parts[2]);
while($debut_parts[0] < $fin_parts[0] || ($debut_parts[0] == $fin_parts[0] && $debut_parts[1] < $fin_parts[1]) ){ // foreach half hour
if($mydata != null){ // if there is already an date recorded
foreach($mydata as $mydataun){ // foreach recorded date
$itime = $mydataun->time;
$jtime = explode(":", $itime);
$jtime[0] = intval($jtime[0]);
$jtime[1] = intval($jtime[1]);
$jtime[2] = intval($jtime[2]);
if(strval($jtime[0]).":".strval($jtime[1]).":".strval($jtime[2]) == strval($debut_parts[0]).":".strval($debut_parts[1]).":".strval($debut_parts[2])){
if($debut_parts[1]== 0 && $mydataun->duration == 1){
$debut_parts[1]+=30;
}elseif($mydataun->duration == 1){
$debut_parts[0]+=1;
$debut_parts[1]=0;
}
}else{
echo "<a href=\"https://someaddress/?page_id=24&mydate=".$_GET['mydate']."&myuser=".$_GET['myuser']."&myform=".$_GET['myform']."&mytime=".strval($debut_parts[0]).":";
if($debut_parts[1]==0){
echo "00:00";
}else{
echo "30:00";
}
echo "\">".$debut_parts[0].":";
if($debut_parts[1]==0){
echo "00:00";
}else{
echo "30:00";
}
echo "</a></br>";
}
}
}else{
echo "<a href=\"https://someaddress/?page_id=24&mydate=".$_GET['mydate']."&myuser=".$_GET['myuser']."&myform=".$_GET['myform']."&mytime=".strval($debut_parts[0]).":";
if($debut_parts[1]==0){
echo "00:00";
}else{
echo "30:00";
}
echo "\">".$debut_parts[0].":";
if($debut_parts[1]==0){
echo "00:00";
}else{
echo "30:00";
}
echo "</a></br>";
}
if($debut_parts[1]== 0){
$debut_parts[1]+=30;
}else{
$debut_parts[0]+=1;
$debut_parts[1]=0;
}
}
}
do_action( 'generate_after_main_content' );
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
/**
* generate_after_primary_content_area hook.
*
* #since 2.0
*/
do_action( 'generate_after_primary_content_area' );
generate_construct_sidebars();
get_footer();
echo "<a href=\"https://someaddress/?page_id=24&mydate=".$_GET['mydate']."&myuser=".$_GET['myuser']."&myform=".$_GET['myform']."&mytime=".strval($debut_parts[0]).":";
if($debut_parts[1]==0){
echo "00:00";
}else{
echo "30:00";
}
echo "\">".$debut_parts[0].":";
if($debut_parts[1]==0){
echo "00:00";
}else{
echo "30:00";
}
echo "</a></br>";
Have to be at the end of while loop
<?php
date_default_timezone_set('America/New York');
$servermonth = date('m/d/Y ', time());
$createdate = new DateTime($row['createdon']);
$newdateformat =$createdate->format('m/d/Y') ;
// echo $newdateformat;
// echo $servermonth;
if (servermonth == newdateformat) {
?>
<span class="label label-default">New</span>
<?php
}
?>
basically it should show the "New " icon when the date is created today. they are both echo-ing the same date but the span is not showing up
Try using this:
if (strtotime(servermonth) === strtotime(newdateformat)) {
echo '<span class="label label-default">New</span>';
}
<?php
date_default_timezone_set('America/New York');
$servermonth = date('m/d/Y ', time());
$createdate = new DateTime($row['createdon']);
$newdateformat =$createdate->format('m/d/Y') ;
// echo $newdateformat;
// echo $servermonth;
if (strtotime($servermonth) == strtotime($newdateformat)) { ?>
<span class="label label-default">New</span>
<?php } ?>
It should be:
<?php
date_default_timezone_set('America/New York');
$servermonth = date('m/d/Y ', time());
$createdate = new DateTime($row['createdon']);
$newdateformat = $createdate->format('m/d/Y') ;
// echo $newdateformat;
// echo $servermonth;
if (strtotime($sservermonth) == strtotime($newdateformat)) {
echo '<span class="label label-default">New</span>'
}
?>
I'd like to add "selected" attribute to a combo box. This is my PHP:
if($results['status'] == 1)
{ $ok1= "selected"; }
else
{ $ok1= ""; }
if($results['status'] == 2)
{ $ok2= "selected"; }
else
{ $ok2= ""; }
if($results['status'] == 3)
{ $ok3= "selected"; }
else
{ $ok3= ""; }
if($results['status'] == 4)
{ $ok4= "selected"; }
else
{ $ok4= ""; }
I may have over hundreds of IF's.
I've tried this one, but It seems not working:
for($a=1; $a<=4; $a++){
if($results['status'] == $a)
{ $ok = "selected"; }
else
{ $ok = ""; }
}
I'd like to make it as simple as possible. maybe 1 or 2 line. Because I have many combo box that should be treated this way
Edit (My combo box):
<select>
<option value="1" <?php echo $ok1; ?>>A</option>
<option value="2" <?php echo $ok2; ?>>B</option>
<option value="3" <?php echo $ok3; ?>>C</option>
<option value="4" <?php echo $ok4; ?>>D</option>
</select>
Since $results['status'] can only have 1 value, use dynamic variable names to make your life easy!
// initialize all 4 to blank
for($a=1; $a<=4; $a++){
${"ok" . $a} = "";
}
// set the one that is selected
${"ok" . $results['status']} = "selected";
This answer is very scalable, you can just change the number on the "for" line from 4 to 1000 and it works with no extra code added.
You can do this way,
<?php
// status list array
$selectValues = array(1, 2, 3, 4);
echo '<select name="combo_name">';
foreach($selectValues as $value){
$selected = "";
if($results['status'] == $value){
$selected = ' selected="selected" ';
}
echo '<option '.$selected.' value="'.$value.'">'.$value.'</option>';
}
echo '</select>';
?>
All you have to do is make an array and loop through it-
<?php
$results_status = 3; // What ever your retrieve variable value is. In your case: `$results['status']`
$arr = array("1" => "A",
"2" => "B",
"3" => "C",
"4" => "D"
);
?>
<select>
<?php
foreach($arr as $key => $val){
$sel = ($results_status == $key) ? "selected='selected'" : "";
?>
<option value="<?php echo $key?>" <?php echo $sel; ?>><?php echo $val?></option>
<?php }?>
</select>
You need to check every time for the selected value in the combo box.
Hope this helps
$combolength - the number of options in combo
$ok = array_fill(0, $combolength - 1, '');
switch ($results['status']) {
case $results['status']:
$ok[$results['status']]= 'selected';
break;
}
I personally think "simplify" what you already have is not the way to go about this. If you are not using a framework, I think you should instead ask how to make your script reusable, especially since you say "I have many combo box(es) that should be treated this way." Not using a contained element like a function/method sounds like a lot of extra work from a hardcoding standpoint. I personally would create a class that you can make form fields standardized and that you can feed an array into with dynamic key/value arrays. Simple example:
/core/classes/Form.php
class Form
{
# The idea here is that you would have many methods to build form fields
# You can edit this as you please
public function select($settings)
{
$class = (!empty($settings['class']))? ' class="'.$settings['class'].'"':'';
$id = (!empty($settings['id']))? ' id="'.$settings['id'].'"':'';
$selected = (!empty($settings['selected']))? $settings['selected']:false;
$other = (!empty($settings['other']))? ' '.implode(' ',$settings['other']):'';
ob_start();
?>
<select name="<?php echo $settings['name']; ?>"<?php echo $other.$id.$class; ?>>
<?php foreach($settings['options'] as $key => $value) { ?>
<option value="<?php echo $key; ?>"<?php if($selected == $key) echo ' selected'; ?>><?php echo $value; ?></option>
<?php } ?>
</select>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
}
To use:
# Include the class
require_once(__DIR__.'/core/classes/Form.php');
# You can use $form = new Form(); echo $form->select(...etc.
# but I am just doing this way for demonstration
echo (new Form())->select(array(
'name'=>'status',
'class'=>'classes here',
'id'=>'select1',
'other'=>array(
'data-instructions=\'{"stuff":["things"]}\'',
'onchange="this.style.borderColor=\'red\';this.style.fontSize=\'30px\'"'
),
# Options can be assign database returned arrays
'options'=>array(
'_'=>'Select',
1=>'A',
2=>'B',
3=>'C',
4=>'D'
),
'selected'=>((!empty($results['status']))? $results['status'] : '_')
));
Gives you:
<select name="status" data-instructions='{"stuff":["things"]}' onchange="this.style.borderColor='red';this.style.fontSize='30px'" id="select1" class="classes here">
<option value="_">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
I Wanted to make a function from where i can get date , month , year
but i m unable to write functions for that also i don't know how to call those function in Drop down menus
for example
function get_date(){
for($i=1;$i<31;$i++){?>
<?php return '<option value="$i"> $i </option>';
}
now if i called it in select menu
<select >
echo get_date();
</select>
it returns echo $i kindly guide me where i went wrong
Try This
<?php
function get_date()
{
$var="";
for ($i = 1; $i < 31; $i++) {
$num_padded=sprintf("%02d", $i);
$var .='<option value="'.$i.'"> '.$num_padded.' </option>';
}
return $var;
}
?>
<select >
<?php echo get_date(); ?>
</select>
This one for month
<?php
function get_month()
{
$var="";
for ($m=1; $m<=12; $m++) {
$var .= '<option value="'.$m.'">'.date('F', mktime(0,0,0,$m, 1, date('Y'))).' </option>';
}
return $var;
}
?>
<select >
<?php echo get_month(); ?>
</select>
This one for Year
<?php
function get_year($start,$end){
$var="";
while($start <= $end){
$var .="<option value=".$start.">".$start."</option>";
$start++;
}
return $var;
}
?>
<select >
<?php echo get_year(1988,2000); ?>
</select>
Using variables in strings only works when using double quotes ("). Try this:
function get_date(){
$dates = "";
for($i=1;$i<31;$i++){
$dates .= "<option value='$i'> $i </option>";
}
return $dates;
}
Also, there is no need to use php tags in functions.
To call the function you need to put the echo between php tags
<select>
<?php echo get_date(); ?>
</select>
Create a string with all options and then return
function get_date(){
$options = "";
for($i=1;$i<31;$i++){
$options .= "<option value='$i'>$i</option>";
}
return $options;
}
And then print like this
<select name="nameofdropdown" id="idofdropdown">
<?php echo get_date(); ?>
</select>
Check your errors
If you return if immediate return and stop iterations.
Php variables inside singel quotes will not evaluates like '$i' it must be "$i" or "'$i'"within single qotes
Use php tag <?php ?> to print function returned value.
try this
function get_date(){
$date = "";
for($i=1;$i<31;$i++){
$date .= '<option value="'.$i.'>'.$i.'</option>';
}
return $date;
}
Try
function get_date(){
for($i=1;$i<31;$i++){?>
<?php return '<option value="'.$i.'"> '.$i.' </option>';
}
I have a form in PHP. It is unsorted. I would like to sort it. How would I go by it. This is the following PHP code I have. Thanks for help in advance.
<select id="school_name" name="school_name">
<option value="">Select School</option>
<?php for($c=0; $c<sizeof($school_details); $c++){?>
<option value="<?php echo stripslashes($school_details[$c]["title"]); ?>"
<?php if($school_details[$c]["title"]==$appInfo["school_name"]){?> selected="selected" <?php } ?> ><?php echo stripslashes($school_details[$c]["title"]); ?>
</option>
<?php } ?>
</select>
try somthing like this:
$str = "<select id='school_name' name='school_name'>";
$options = "";
for($i = 0; $i<10;$i++)
{
$RandomNum = rand(0, 100);
$options = "" . $options . ("<option value='$RandomNum'> " . $RandomNum . "  </option>\n");
}
$optionsArray = explode("\n", $options);
natsort($optionsArray);
$sorted_option = implode("|",$optionsArray);
$select = $str.$sorted_option."</select>";
echo $select;
PHP provides a number of methods for sorting: http://www.php.net/manual/en/array.sorting.php
You could implement a user defined sort to achieve this. Assuming you want to sort by the value of the 'title' element you would simply add this before your opening select tag:
<?php
uasort($school_details,'cmp');
function cmp($a,$b){
if($a['title'] == $b['title']){return 0;}
return ($a['title'] < $b['title']) ? -1 : 1;
}
?>