PHP Concatenate Zero to date POST value - php

I need to add a zero to the date value that is posted as the MySQL date value will be used as a directory path to show added photos. Currently the directory is saved as 2012-2-5 and the MySQL entry is 2012-02-05.
I have tried the following, however it doesn't seem to be working:
$dates = array($_POST['photos_year'], $_POST['photos_month'], $_POST['photos_day']);
foreach($dates as $date) {
if (strlen($date) == 1) {
$date = '0' . $date;
}
}
$photos->date = $dates[0] . "-" . $dates[1] . "-" . $dates[2];
I am using a for loop to create the date form, it might be easier for me to edit this however I haven't had any success:
<select name="photos_month" id="photos_month" tabindex="3">
<option value ="">- Month -</option>
<?php
for($date=01;$date<=12;$date++) {
if (isset($photos) && $date==$month) {
echo "<option value='".$date."' selected='selected'>".$date."</option>";
} else {
echo "<option value='".$date."'>".$date."</option>";
}
}
?>
</select>

You need to update the foreach to be
foreach ($dates as &$date)
Currently, $date is a new symbol and will not overwrite the value. That should fix it, but it may be nice to have the correct strings in the options too. You can use str_pad to do that.

When doing a foreach, the element variable $date is a new variable, a copy of the value from the array. You should use a key and update the original array.
foreach($dates as $key => $date) {
if (strlen($date) == 1) {
$dates[$key] = '0' . $date;
}
}
Also, you're running that code on the year, you don't want to be adding a zero to the year, only the month and day.

You could make it a little simpler by just using sprintf with a format string;
$photos_year = '2012';
$photos_month = '2';
$photos_day = '5';
$result = sprintf("%4d-%02d-%02d", $photos_year, $photos_month, $photos_day);
// $result = '2012-02-05'

Check out the string pad function http://php.net/manual/en/function.str-pad.php
Along with the array map function http://php.net/manual/en/function.array-map.php
Using these two together would allow for you to go through each part of the date(array_map) and pad the value with a 0 (using str_pad)
Code would look something like this
$dates = array_map("padString",$dates);
function padString($string) {
return str_pad($string,2,"0",STR_PAD_LEFT);
}
print_r($dates);
//Gives you Array ( [0] => 2012 [1] => 02 [2] => 05 )

use sprintf()
For example:
$date = sprintf('%02d', $_POST['photos_day']);

Related

How to remove values from an array in Laravel

I am trying to make a really basic day booking system and need to return all dates within a range, and then remove selected dates from that range. I tried the following code but realised that will remove duplicates which is fine, but I also need that date to be removed too.
Can anyone suggest a good way of doing this?
In the below example I am just hoping to see:
2022-04-03T00:00:00.000000Z
2022-04-04T00:00:00.000000Z
2022-04-05T00:00:00.000000Z
$start_date = "2022-04-01";
$end_date = "2022-04-05";
$datesToRemove = [
'2022-04-01T00:00:00.000000Z',
'2022-04-02T00:00:00.000000Z'
];
$range = Carbon::parse($start_date)->toPeriod($end_date)->toArray();
$available = array_unique(array_merge($range, $datesToRemove));
return $available;
To compare it is necessary to have the compared values in the same format. I decide to morph the $datesToRemove to Carbon format. The you can use to nested loops and check with PHP in_array() function.
$start_date = "2022-04-01";
$end_date = "2022-04-05";
$datesToRemove = [
"2022-04-01T00:00:00.000000Z",
"2022-04-02T00:00:00.000000Z"
];
$range = \Carbon\Carbon::parse($start_date)->toPeriod($end_date)->toArray();
$datesToRemove2 = [];
foreach($datesToRemove as $r) {
$datesToRemove2[] = \Carbon\Carbon::parse($r);
}
$res = [];
foreach($datesToRemove2 as $index => $d1) {
if(in_array($d1, $range)) {
unset($range[$index]);
}
}
return $range;
output
{
"2":"2022-04-03T00:00:00.000000Z",
"3":"2022-04-04T00:00:00.000000Z",
"4":"2022-04-05T00:00:00.000000Z"
}
Means that

nearest date in php strtotime

I have several date(strtotime) in a Variable and want the first nearest date that is after the specified date(my date) with php. what do i do?
Variable:
$varD = "1481691600,1482642000,1482037200";
my date:
1481778000 => (2016-12-15)
several date(strtotime):
1481691600 => (2016-12-14)
1482642000 => (2016-12-25)
1482037200 => (2016-12-18) //result
result:
1482037200 => (2016-12-18)
$varD = "1481691600,1482037200,1482642000";
$myDate = "1481778000";
After you explode the string of timestamps ($varD), you can filter them and return the minimum value of the result. Here is one way to do that using array_filter and min.
$comp = function($x) use ($myDate) { return $x > $myDate; };
$firstDateAfterYours = min(array_filter(explode(',', $varD), $comp));
But if you already know that the timestamps in the string will be in ascending order, it will probably be faster not to convert the whole thing to an array and sort through it. You can use strtok to go through it piece by piece and just stop as soon as you get to a timestamp larger than your target.
$ts = strtok($varD, ',');
while ($ts !== false) {
$ts = strtok(',');
if ($ts > $myDate) break;
}
$firstDateAfterYours = $ts;

How can I store dates on a multi-dimensional associative array?

How can I store dates on a multi-dimensional associative array?
I can't explain further my problem, but what if I have an array that contains different dates. For example:
<?php
$dates = array("2015-06-01","2015-06-07","2015-07-08","2015-08-01", "2015-08-21","2015-08-26");
?>
I want to store the array above into multi dimensional associative array, according to their month, so therefore it would be like this..
<?php
array = array(
"June" => array("2015-06-01","2015-06-07"),
"July"=> array("2015-07-08"),
"August" => array("2015-08-01","2015-08-21","2015-08-26")
);
?>
But in my case, the dates are from the database compare to the example above that are defined dates, how can I group that following dates according to their month and store in an associative array named according to their month and the content is the second dimensional array that contains the date grouped?
Thanks!
My code above are just example: This is my solution but it's not working good! -_-
<?php
include($_SERVER["DOCUMENT_ROOT"] . "/empc/library/functions.php");
$previousmonth = "";
$a = getDistinctDates(); // Function that get dates, nevermind of this.
$data = array();
foreach ($a as $b){
echo $b["date_modified"] . "<br>";
$datemonth = date("F",strtotime($b["date_modified"]));
echo $datemonth . "<br>";
if ($datemonth != $previousmonth){
array_push($data,
array(
$datemonth => $b["date_modified"]
)
);
} else {
array_push($data[$datemonth][],$b["date_modified"]);
}
echo $b["balance_after_approval"] . "<br>";
echo "<br>";
$previousmonth = $datemonth;
}
?>
your over thinking this, just use the month as the array key:
<?php
$dates = array("2015-06-01","2015-06-07","2015-07-08","2015-08-01", "2015-08-21","2015-08-26");
$out=array();
foreach ($dates as $b){
$datemonth = date("F",strtotime($b));
$out[$datemonth][]=$b;
}
print_r($out);
?>
demo:http://codepad.viper-7.com/3Gh9s7

How to split the time from a timestamp from a nested array of result?

I have been doing a project in php and i get a nested array from where i have to extract the values.
Here from this array i have to get only the time from the timestamp i.e from [ArrTime] and [DepTIme]
[Segment] => stdClass Object
(
[WSSegment] => stdClass Object
(
[DepTIme] => 2014-12-10T15:40:00
[ArrTime] => 2014-12-10T18:25:00
[ETicketEligible] => 1
[OperatingCarrier] => HW
)
)
I have being trying to apply the implode function on the timestamp but it is not working for me .
Try this one:
$DeptTime = date('H:i:s',strtotime($yourObject->Segment->WSSegment->DepTIme));
$ArrTime = date('H:i:s',strtotime($yourObject->Segment->WSSegment->ArrTime));
Write a function to retrieve it in php
<?php
$str = '2014-12-10T15:40:00';
function getOnlyTime($str = '') {
$time = '';
if (empty($str)) {
return $time;
}
return substr($str, 11);
}
echo getOnlyTime($yourObject->Segment->WSSegment->DepTIme);
echo getOnlyTime($yourObject->Segment->WSSegment->ArrTime);
?>
Live Example:
http://3v4l.org/1qChm
You could loop through the nested objects and see if the format matches a date. If it does, make an array of the matched elements. You could choose to index the array according to the index where it came from (if that matters later on in your code;
// Starts at "Segment"
foreach ($array as $segment => $item)
{
// Loops through the values of"WSSegment"
foreach ($item as $part => $value)
{
// Checks if the value is a valid date, might need to check type; $value must be a string
if ($date = date_create_from_format('Y-m-d\TH:i:s', $value))
{
// Dump to an array.
$dates[$part][] = $date;
}
}
}
$dates is now an array containing all valid dates in \DateTime format.
Here's another way that I recommend for several reasons. It saves one from having to manually extract the data by using substr() or explode(). The code uses two foreach loops to 'drill down to the desired items, namely the departure and arrival date-time data. If any of the names of the nested objects were to change, the code will still run since it makes use of variables in referring to those entities. Using a DateTime object's format property provides a handy way to access just the time information and you can easily exclude the seconds as the following example illustrates:
<?php
/**
* getTime()
* #param $str - date/time string
* returns time in hours and minutes
**/
function getTime( $str ){
$format = "H:i"; // Hours:Minutes
$timeObj = new DateTime( $str );
return $timeObj->format( $format );
}
foreach( $obj as $nested ) {
foreach( $nested as $n ){
echo 'DEP - ',getTime( $n->DepTime ),"\n";
echo 'ARV - ',getTime( $n->ArrTime ),"\n";
}
}
See http://3v4l.org/IdQN1

How do I get max(); to display the highest value number rather than just "Array"?

max($caption);
gives me this:
Array
$caption is defined here:
$i = "0";
while ($i < $count) {
list($oldCaption, $year, $order) = explode("-", $galleryDirectory[$i]);
$caption[$year][$order] = str_replace("_", " ", "$oldCaption");
echo $year; //debug
echo "<br />";
$i++;
}
$year comes out to be
2008
2009
2009
so how do I get max($caption); to give me the value of 2009 rather than Array?
also i would put the whole code, but when i tried that it turned out messy. but I will try again, so you guys can see the whole pictures
Use array_keys():
$years = array_keys($caption);
$maxYear = max($years);
// or the one-liner:
$maxYear = max(array_keys($caption));
The reason why your code wasn't working is that you were comparing the values of the array $caption, which is an another array. max() compares int values, not keys nor arrays. By using array_keys() on $caption creates another array with all years as values.

Categories