I was wondering if there is a better solution to loop through an array from mid to end then from start to mid. Particularly for an associative array.
So for example if there is an associative array with the keys
$dow = array(Mon => etc, Tue => etc, Wed => etc, Thr => etc .. to .. Sun => etc).
I would start searching the array from Thurs to find the next day with something specific which could be anyday but happens to be on Tues, I usually iterate from Thurs (by index) to Sunday then, reset and start again from Monday to Wed and find the target when reaching Tues.
I count the index via an id and when it reaches 6 reset the id to 0
$id = 3 // Found day is Thursday id
//Loop function starts here
$id++; // start search from one day above found day
if ($id >= 6){ //when reaching Sunday
$id = 0 // start search from monday
}
// check array here for that specific thing
So the question is to ask if there is a more simple solution than this, ie split array from index thursday to sunday and add it onto the beginning of the array and then do the loop without having to count an index or if there are any other solutions without using the count index.
You can try with array_splice:
$array = array(1,2,3,4,5,6,7);
$lastDays = array_splice($array, 3);
$firstDays = $array;
print_r(array('first days' => $firstDays, 'last days' => $lastDays));
If the day is not in $lastDays (use a boolean like $matchFound) then you would search in $firstDays.
Or just use with array_merge:
$array = array(1,2,3,4,5,6,7);
$array = array_merge(array_splice($array, 3), $array);
print_r($array);
where output is:
Array
(
[0] => 4
[1] => 5
[2] => 6
[3] => 7
[4] => 1
[5] => 2
[6] => 3
)
and then you can search with a foreach.
maybe a foreach would be more efficient. hope this helps.
$id = 3 // Found day is Thursday id
$i =0;
//Loop function starts here
foreach($dow as $idx)
if($id == $i):
else if($i > $id):
endif;
if($i == count($dow)){$i=0;}else{$i++;}
endforeach;
<?php
$dow = array("mon","tue","wed","thu","fri","sat","sun");
$pick_a_day = 2; // user input; NON zero based. monday = 1
$pick_a_day--; // make it zero based to use in code
foreach($dow as $inc => $an_element )
{
echo $dow[($pick_a_day+(count($dow))) % (count($dow))]." - loop number:".($inc+1)."\n";
$pick_a_day++;
}
?>
output
tue - loop number:1
wed - loop number:2
thu - loop number:3
fri - loop number:4
sat - loop number:5
sun - loop number:6
mon - loop number:7
Maybe not the best solution, but a solution:
function half($array) {
$h = sizeof($array) / 2;
$a1 = array_splice($array, $h);
$a2 = array_splice($array, 0);
$res = array_merge($a1, $a2);
return $res;
}
$dow = array('Mon' => 'etc1', 'Tue' => 'etc2', 'Wed' => 'etc3', 'Thr' => 'etc4', 'Fri' => 'etc5', 'Sat' => 'etc6', 'Sun' => 'etc7');
$b = half($dow);
Now you can go through with a foreach, or how would you like. Result of $b:
Array
(
[Thr] => etc4
[Fri] => etc5
[Sat] => etc6
[Sun] => etc7
[Mon] => etc1
[Tue] => etc2
[Wed] => etc3
)
Related
$dates = array('2017-03-24 01:48:09', '2017-03-24 11:48:09', '2017-04-07 01:12:19', '2017-04-14 01:49:09', '2017-04-21 01:45:09', '2017-04-28 01:38:09');
if given array above..
i'm making a report to monitor user growth monthly.. i want to count the no. of entries per month
sample April 2 counts
$dates = array('2017-03-24 01:48:09', '2017-03-24 11:48:09', '2017-04-07 01:12:19', '2017-04-14 01:49:09', '2017-04-21 01:45:09', '2017-04-28 01:38:09');
$count = array();
foreach ($dates as $d) {
$count[date('m', strtotime($d))]++;
}
print_r($count);
Output will be:
Array ([03] => 2 [04] => 4 )
That is: 03 (March) has 2 values in given array.
If you need 03 as March, then use:
$count[date('F', strtotime($d))]++;
Then, output will be:
Array ([March] => 2 [April] => 4 )
<?php
$dates = array('2017-03-24 01:48:09', '2017-03-24 11:48:09', '2017-04-07 01:12:19', '2017-04-14 01:49:09', '2017-04-21 01:45:09', '2017-04-28 01:38:09');
foreach($dates as $date)
$year_months[] = date('Y-m', strtotime($date));
var_export($year_months);
var_export(array_count_values($year_months));
Output:
array (
0 => '2017-03',
1 => '2017-03',
2 => '2017-04',
3 => '2017-04',
4 => '2017-04',
5 => '2017-04',
)array (
'2017-03' => 2,
'2017-04' => 4,
)
I have an array of dates like this:
[Room 01 - DBL] => Array
(
[0] => Mon 23-06-2014
[1] => Tue 24-06-2014
[2] => Wed 25-06-2014
[3] => Sat 28-06-2014
[4] => Sun 29-06-2014
)
[Room 02 - TWN] => Array
(
[0] => Tue 24-06-2014
[1] => Wed 25-06-2014
[2] => Sat 28-06-2014
[3] => Sun 29-06-2014
)
You can see that neither room has the date for the thursday or friday. I want to be able to create a date range (either a DateTime Interval object or not - don't mind) for each group of dates. So Room 02 - TWN should give me two date periods - one for Tue-Wed and another for Sat-Sun. How would I go about this? I know how to make a single date time period using the first and last items in the array but don't know how to detect if there is a gap...
I'm not very clear about what you're trying to accomplish. Anyway, in the general case, you can do something like this.
The idea is to run the whole array of items, and if the "next" item is contiguous to a candidate interval you already have, you extend the interval. Else, the candidate interval becomes a standalone interval, and the item that just failed the check gives birth to a new candidate interval.
You need two functions: one that, given two items, returns whether it's true or false that they are contiguous; the other, given two items, returns an "interval" with those two items as extremes.
An empty $items will return an empty interval.
function build_intervals($items, $is_contiguous, $make_interval) {
$intervals = array();
$end = false;
foreach ($items as $item) {
if (false === $end) {
$begin = $item;
$end = $item;
continue;
}
if ($is_contiguous($end, $item)) {
$end = $item;
continue;
}
$intervals[] = $make_interval($begin, $end);
$begin = $item;
$end = $item;
}
if (false !== $end) {
$intervals[] = $make_interval($begin, $end);
}
return $intervals;
}
For numbers, you can use
$interv = build_intervals(
array( 1, 2, 3, 5, 6, 9, 10, 11, 13, 17, 18 ),
function($a, $b) { return ($b - $a) <= 1; },
function($a, $b) { return "{$a}..{$b}"; }
);
print_r($interv);
returns
Array
(
[0] => 1..3
[1] => 5..6
[2] => 9..11
[3] => 13..13
[4] => 17..18
)
With dates, you can keep them as DateTime and DateTimeIntervals. If you use timestamps, then you must supply a contiguousness criterion that's valid for timestamps. This can be awkward if you have two timestamps that are just before and after midnight the following day. To be sure, you should take times at always around midday (i.e., given two dates, get the timestamps of those dates at midday. If they're less than 36 hours apart, they're two adjacent days.
function($a, $b) {
$a_ts = strtotime("{$a} 12:00:00");
$b_ts = strtotime("{$b} 12:00:00");
return ($b - $a) <= (36 * 60 * 60);
},
I have a script that builds an array of week numbers for the last 12 weeks like so:
$week_numbers = range(date('W'), date('W')-11, -1);
However, if the current week number is 1, then this will return an array like so:
Array
(
[0] => 1
[1] => 0
[2] => -1
[3] => -2
[4] => -3
[5] => -4
[6] => -5
[7] => -6
[8] => -7
[9] => -8
[10] => -9
[11] => -10
)
But I need this array to look like this instead:
Array
(
[0] => 1
[1] => 52
[2] => 51
[3] => 50
[4] => 49
[5] => 48
[6] => 47
[7] => 46
[8] => 45
[9] => 44
[10] => 43
[11] => 42
)
Can anyone see a simple solution to this?
I have thought about doing something like this (not tested):
$current_week_number = date('W');
if($current_week_number<12){
// Calculate the first range of week numbers (for current year)
$this_year_week_numbers = range(date('W'), 1, -1);
// Calculate the next range of week numbers (for last year)
$last_year_week_numbers = range(52, 52-(11-$current_week_number), -1);
// Combine the two arrays to return the week numbers for the last 12 weeks
$week_numbers = array_merge($this_year_week_numbers,$last_year_week_numbers);
}else{
// Calculate the week numbers the easy way
$week_numbers = range(date('W'), date('W')-11, -1);
}
one idea
$i = 1;
while ($i <= 11) {
echo date('W', strtotime("-$i week")); //1 week ago
$i++;
}
if you arent scared of loops you can do this:
$week_numbers = range(date('W'), date('W')-11, -1);
foreach($week_numbers as $key => $value) { if($value < 1) $week_numbers[$key] += 52; }
You can do a modulo % trick:
$week_numbers = range(date('W'), date('W')-11, -1);
foreach ($week_numbers as $i => $number) {
$week_numbers[$i] = (($week_numbers[$i] + 52 - 1) % 52) + 1;
}
// -1 +1 is to change the range from 0-51 to 1-52
I've found that using modulo like this is often useful for date calculations, you can something similar for months, using 12.
Well, I think the easiest way is to create array after getting dates:
$week_numbers = array_map(function($iDay)
{
return ($iDay+52)%52?($iDay+52)%52:52;
}, range(date('W'), date('W')-11));
-note, that you can not do just % since 52%52 will be 0 (and you want 52)
I have an array which represent all month. How can I find today's day in the array, take that day, plus next six days (not necessary six days) and remove rest from the array?
For example:
$days = array('1', '2', '3', ... '28', '29', '30');
I need 3-9. How can I do this?
I think you should look at another way of doing whatever it is you want to do. But here is a solution for what you asked:
$days = range(1, date('t'));
$days_forward = 6;
$key = array_search(date('j'), $days);
if($key === FALSE)
die('Date not found in array');
$days = array_slice($days, $key, $days_forward + 1);
print_r($days);
Output:
Array
(
[0] => 19
[1] => 20
[2] => 21
[3] => 22
[4] => 23
[5] => 24
[6] => 25
)
I have an array that is produced from people wanting to reserve a time block to volunteer with our organization. I want to check to see if they chose time blocks on the same day that overlap. In my example array below the first and third elements are overlapping and I need to detect that. Any recommendation would be much appreciated:
Array
(
[0] => Array
(
[id_pc_time_blocks] => 3
[id_pc] => 2
[pc_date] => 2012-11-21
[pc_time_block] => 9:00 AM-1:00 PM
[pc_time_block_max] => 25
[pc_time_block_count] => 0
[pc_name] => Atlanta
)
[1] => Array
(
[id_pc_time_blocks] => 4
[id_pc] => 2
[pc_date] => 2012-11-21
[pc_time_block] => 1:00 PM-5:00 PM
[pc_time_block_max] => 25
[pc_time_block_count] => 10
[pc_name] => Atlanta
)
[2] => Array
(
[id_pc_time_blocks] => 6
[id_pc] => 2
[pc_date] => 2012-11-21
[pc_time_block] => 10:00 AM-2:00 PM
[pc_time_block_max] => 25
[pc_time_block_count] => 0
[pc_name] => Atlanta
)
[3] => Array
(
[id_pc_time_blocks] => 6
[id_pc] => 2
[pc_date] => 2012-11-23
[pc_time_block] => 10:00 AM-2:00 PM
[pc_time_block_max] => 25
[pc_time_block_count] => 0
[pc_name] => Atlanta
)
[4] => Array
(
[id_pc_time_blocks] => 6
[id_pc] => 2
[pc_date] => 2012-11-23
[pc_time_block] => 3:00 AM-6:00 PM
[pc_time_block_max] => 25
[pc_time_block_count] => 0
[pc_name] => Atlanta
)
)
Not recommended for HUGE arrays, but here's a quick solution. You need to break hte times into unix time stamps for comparisson
// Run down each element of the array. (I've called it MyStartArray)
$numElements = count($MyStartArray);
for ($i=0; $i<$numElements ; $i++) {
// Calculate "Start Time" and "End Time" as Unix time stamps (use mktime function) and store as another items in the array
// You can use preg_match or substr to get the values to pump into mktime() below - not writing hte whole thing for you ;)
$MyStartArray[$i]['start_time'] = mktime( ... );
$MyStartArray[$i]['end_time'] = mktime( ... );
// Now run through all the previous elements to see if a start time is before the end time, or an end time is after the start time.
if ($i > 0) {
for ($j=0; $j<$i;$j++) {
if ($MyStartArray[$i]['start_time'] < $MyStartArray[$j]['end_time'] ||
$MyStartArray[$j]['end_time'] > $MyStartArray[$j]['start_time'] ) {
echo 'CLASH';
}
}
}
}
Here is my solution for checking each date for overlapping times. The only thing is, this is for my particular scenario and does not account for overlapping years as I dont have that need for this application.
Here is my working example:
$dateIdx = 0;
foreach($timeblocks_array as $obj) {
$timeblocks_array[$dateIdx]["intDay"] = idate("z",strtotime($obj["pc_date"]));
$timeblocks_array[$dateIdx]["intStart"] = intval($obj["start_time"]);
$timeblocks_array[$dateIdx]["intEnd"] = intval($obj["end_time"]);
$mindates[] = idate("z",strtotime($obj["pc_date"]));
$dateIdx++;
}
$minDateSingle = min($mindates);
$maxDateSingle = max($mindates);
$currentDate = $minDateSingle;
$dateIdx = 0;
while ($currentDate <= $maxDateSingle) {
$hrIndex = 0;
while ($hrIndex < 24) {
$matrixArray[$dateIdx][$hrIndex]["count"] = 0;
$matrixArray[$dateIdx][$hrIndex]["intDay"] = $currentDate;
$hrIndex++;
}
// calculate counts:
$hourIdx = 0;
foreach($matrixArray[$dateIdx] as $hour){
foreach($timeblocks_array as $block) {
if ($hour["intDay"] == $block["intDay"]) {
if ($hourIdx >= $block["intStart"] && $hourIdx < $block["intEnd"]) {
$matrixArray[$dateIdx][$hourIdx]["count"] = $matrixArray[$dateIdx][$hourIdx]["count"] + 1;
$matrixArray[$dateIdx][$hourIdx]["requests"][] = $block;
}
}
}
$hourIdx++;
}
$dateIdx++;
$currentDate = $currentDate + 1;
}
//loop through the matrix array and timeblocks array to see if they intersect
foreach($matrixArray as $day) {
$hourIdx = 0;
foreach($day as $hour) {
if ($hour["count"] > 1) {
//echo $hour["intDay"]." - Overlap on Hour $hourIdx\n";
$smarty->assign('overlappingError', 1);
$error = 1;
foreach($hour["requests"] as $overlapblock) {
//echo " --> conflict: ". $overlapblock["pc_date"]." ".$overlapblock["pc_time_block"]." (".$overlapblock["intStart"]." to ".$overlapblock["intEnd"].")\n";
}
} else if ($hour["count"] == 1) {
// these are valid hours
}
$hourIdx++;
}
}
Robbie's answer did not work for me. I found the rules that needed to be in place going off his example for just dates were:
$i[start] needs to be less than and not equal to $i[stop]
$i[start] needs to greater than and not equal to $j[stop]
$j[start] needs to be less than and not equal to $j[stop]
Therefore my solution was:
$numElements = count($dates);
for ($i=0; $i<$numElements; $i++) {
$dates[$i]['start_time'] = strtotime($dates[$i]['start']);
$dates[$i]['end_time'] = strtotime($dates[$i]['end']);
if ($i > 0) {
for ($j=0; $j<$i;$j++) {
if($dates[$i]['start_time'] >= $dates[$i]['end_time'] || $dates[$i]['start_time'] <= $dates[$j]['end_time'] || $dates[$j]['start_time'] >= $dates[$j]['end_time']) {
$this->set_error(['dates_overlap']);
$this->dates_overlap = true;
break;
}
}
}
if(isset($this->dates_overlap))
break;
}