continuously loop through PHP array (or object keys) - php

I have a series of object keys:
$this->rules->days->mon = isset($this->recurring_event_data['post_ar'][$this->rules->type]['mon']) ? true : false;
$this->rules->days->tue = isset($this->recurring_event_data['post_ar'][$this->rules->type]['tue']) ? true : false;
$this->rules->days->wed = isset($this->recurring_event_data['post_ar'][$this->rules->type]['wed']) ? true : false;
$this->rules->days->thu = isset($this->recurring_event_data['post_ar'][$this->rules->type]['thu']) ? true : false;
$this->rules->days->fri = isset($this->recurring_event_data['post_ar'][$this->rules->type]['fri']) ? true : false;
$this->rules->days->sat = isset($this->recurring_event_data['post_ar'][$this->rules->type]['sat']) ? true : false;
$this->rules->days->sun = isset($this->recurring_event_data['post_ar'][$this->rules->type]['sun']) ? true : false;
I have this function:
function calc_next_weekly_interval($ii,$i)
{
global $array;
// we will roll through this->rules->mon,tue,wed,thu,fri,sat,sun. If its true, return the new iii value, if not keep looping through the array until we hit true again.
$cur_day = strtolower(date('D',$ii));
$found_today = false;
// our initial start date
$iii = $ii;
foreach($this->rules->days as $day => $value)
{
if($found_today == true && $value = true)
{
return $iii
}
// need to find the current day first!
if($day == $cur_day)
{
$found_today = true;
}
$iii + SECS_PER_DAY;
}
}
all good. Note I am trying to find the next true day from the current day. Issue is when I do a search using a Sunday as the initial cur_day, obviously the foreach loop will stop before it finds a true match. How can I continuously loop through an array (Or object keys)? Should I put the loop in a new function and keep calling it with a new start date? I don't want to add extra array keys->values as it will affect things later, I have thought about adding to the initial array only in this function (example here, the array is coded for reference, but in my class - it is of course obj keys->values

If you want to loop continually you can use
$infinate = new InfiniteIterator(new ArrayIterator($array));
foreach ( $infinate as $value ) {
// Do your thing
// Remember to break
}

How about
foreach($this->rules->days as $day => $value)
{
if($day == $cur_day)
{
$set = true;
}
$iii + SECS_PER_DAY;
if($found_today == true && $value = true)
{
return $iii
}
// need to find the current day first!
}

Related

Comparing database result and multidimensionnal array

I have arrays and data from a databse, and need to compare them.
$mydays = array(
'Monday' => array('10:00','11:00','12:00','15:00','16:00','17:00','18:00'),
'Tuesday' => array('10:00','11:00','12:00','15:00','16:00','17:00','18:00'),
'Wednesday' => array('9:00','10:00','11:00','12:00','14:00','15:00','16:00','17:00','18:00'),
'Thursday' => array('9:00','10:00','11:00','12:00','14:00','15:00','16:00','17:00','18:00'),
'Friday' => array('9:00','10:00','11:00','12:00','14:00','15:00','16:00','17:00','18:00'),
'Saturday' => array('9:00','10:00','11:00','12:00')
);
$myhours = array(
"2017-02-27" => array("17:00"),
"2017-03-01" => array("16:00","17:00","18:00"),
"2017-03-03" => array("17:00"),
"2017-03-08" => array("17:00","18:00"),
"2017-03-10" => array("17:00","18:00")
);
From a database, I retrieve some data such as :
$thisday = Monday
$thisdate = yyyy-mm-dd
$thishour = H:i
$myday = $mydays[$thisday];
foreach ($myday as $hour) { /* loop through hours for this specific day */
// I need to find out if there is a date/hour from "$myhours" that matches my data
// ie: I have database:Monday -> I loop through the hours from $mydays:Monday
// I then have : 10:00,11:00,12:00,15:00,16:00,17:00,18:00
// from there, I need to know if, in "$myhours", I have the same hour for "$thisdate"
}
I have read almost every post here, found and tried using :
function in_multiarray($elem, $array, $field)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom][$field] == $elem) {
return true;
} else {
if(is_array($array[$bottom][$field])) {
if(in_multiarray_d($elem, ($array[$bottom][$field]))) {
return true; } else { return false; }
} else { return false; }
$bottom++;
}
}
return false;
}
if( !in_multiarray("$thisdate", $myhours, "$hour") ) { echo"good"; } else { echo"not good"; }
My problem : I don't get a result every time (even when some day/hour matches), and when I do, it's not for every hour, I miss some days/hours... I thought I would maybe need to reset the array, but had no better result doing it.
Q: is my approach a correct way to work around my problem ? If yes, what am I doing wrong ? if not, what is you best advice, or what shall I do ?
Simple solution using in_array function:
...
$thisday = 'Monday';
$thisdate = "2017-02-27";
$thishour = '11:00';
// check if we have a valid weekday name and date/time value
if (isset($mydays[$thisday]) && isset($myhours[$thisdate])
&& in_array($thishour, $mydays[$thisday])) {
echo 'good';
} else {
echo "not good";
}

How to check if two times overlap in PHP?

So I'm trying to figure out how to check if two times overlap using PHP and a MySQL database.
This is the function I'm using to check if they are overlapping:
function testRange($start_time1,$end_time1,$start_time2,$end_time2) {
return ($end_time1 < $start_time2) ? false : ($start_time1 > $start_time2) && ($start_time1 > $end_time2) ? false : true;
}
AFAIK that should work fine so I go to check if the times are overlapping and add any that do overlap to an array:
$clashes = [];
$idTracker = [];
foreach ($userBands as $show) {
foreach ($userBands as $show1) {
if(!($show->id == $show1->id)) {
if(strcmp($show->date, $show1->date) == 0 && testRange(strtotime($show->time), strtotime($show->time) + ($show->length*60), strtotime($show1->time), strtotime($show1->time) + ($show1->length*60))) {
array_push($clashes, [
"s1_id" => $show->id,
"s2_id" => $show1->id
]);
}
}
}
}
foreach ($clashes as $clash) {
foreach ($clashes as $clash1) {
//If Clash1->ID1 == Clash2->ID1 then
}
print_r($clash);
echo "<br>";
}
However when I print out the entries of the $clashes array I get this as my output:
which is just wrong completely as this is the contents of the database:
27 and 26 should not be clashing with 25, but they are being tracked into the $clashes array. Why is this happening?
Database Info:
Date is of the Date SQL type, Time is of the Time SQL type and Length is a double(8,2) SQL type
$userBands Info:
The $userBands variable is a Laravel collection of the Show model
First:
You can change the SQL query to get end-time like so:
SELECT *,
ADDTIME(
CONCAT(time,'.0'),
CONCAT(CONCAT(CONCAT( length DIV 60, ':' ), length MOD 60) ,':0.0')
) AS EndTime
FROM `table`;
So now you have a column named EndTime,
So this code can work:
if(strcmp($show->date, $show1->date) == 0 &&
newTestRange(
strtotime($show->time),
strtotime($show->EndTime),
strtotime($show1->time),
strtotime($show1->EndTime)
) ) {
I have no idea why this works:
function newTestRange($start_time1,$end_time1,$start_time2,$end_time2) {
// 12:30:00 13:20:00 12:45:00 13:45:00
// return ($end_time1 < $start_time2) ? false : ($start_time1 > $start_time2) && ($start_time1 > $end_time2) ? false : true;
$ret = false; // its all okay.
if ($start_time1 < $start_time2 ){
if ($end_time1 > $start_time2 ){
$ret = true;echo "\n case1-$start_time1-colide-$start_time2 \n";
}
} else if ($end_time2 > $start_time1){
$ret = true; echo "\n case2-$start_time1-colide-$start_time2 \n";
}
return $ret;
}
but you must consider 4 different scenarios:
So if one event contains another event, you will find it.
Best!
Fixed it by changing the algorithm for comparing the times.
New version:
function testRange($s1, $e1, $s2, $e2) {
return $s1 <= $e2 && $s2 <= $e1;
}
Don't know why this works over the previous one however.

in specific condition set and store a variable until another specific condition

Hello I'm pretty new in programming. I need to solve this problem in php but the solution in any different language will be great. I tryied to solve it with if statement but if condition is changed the variable is gone. Easy example for better understanding.
// possible conditions ( 'cond1', 'cond2', 'cond3', 'cond4','cond5' )
// conditions can be called randomly
I would like to have somethng like this:
$variable = 'off';
since ( $condition == 'cond2' )
$variable = 'on';
until ( $condition == 'cond4' )
The goal is to switch variable 'on' in the 'cond2' condition and hold it on when the others conditions are changing independently on their order until condition is changed to 'cond4' and variable is switched back to 'off'.
Thanks for any suggestions.
I don't think your current concept is realizable in PHP as you cannot listen to variables, you need to actively get notified. So one scenario with the same solution but a different concept would be
class Condition {
private $value;
private $variable = false;
public function setCondition($new_value) {
$this->value = $new_value;
}
public function getCondition() {
return $this->value;
}
public function isVariableSet() {
return ($this->variable === true); //TRUE if $this->variable is true
//FALSE otherwise
}
}
Now in the method setCondition(...) you can listen and actively set the variable.
public function setCondition($new_value) {
switch ($new_value) {
case 'cond2':
$this->variable = true;
break;
case 'cond4':
$this->variable = false;
break;
}
$this->value = $new_value;
}
With this you can use it like the following
$foo = new Condition();
$foo->setCondition('cond1');
var_dump( $foo->isVariableSet() ); //FALSE
$foo->setCondition('cond2');
var_dump( $foo->isVariableSet() ); //TRUE
$foo->setCondition('cond3');
var_dump( $foo->isVariableSet() ); //TRUE
$foo->setCondition('cond4');
var_dump( $foo->isVariableSet() ); //FALSE
Or in your case:
$conditions = array( 'cond1', 'cond2', 'cond3', 'cond4','cond5' );
$cond = new Condition();
foreach ($conditions as $i => $condition) {
$cond->setCondition($condition);
if ($cond->isVariableSet() == true) {
$toggle = 'on';
}
else {
$toggle = 'off';
}
$results[$condition] = $toggle.' ; ';
}
If you don't create the instance of Condition outside the loop, you gain nothing as you create a new object everytime and no state stays. However, exactly that is required.
You can also do this via array_map() and save the foreach()
$conditions = array( 'cond1', 'cond2', 'cond3', 'cond4','cond5' );
$cond = new Condition();
$results = array();
$setCondGetVariable = function($condition) use($cond) {
$cond->setCondition($condition);
if ($cond->isVariableSet() == true) {
$toggle = 'on';
}
else {
$toggle = 'off';
}
return $toggle.' ; ';
};
$results = array_map($setCondGetVariable, $conditions);

I need a more efficient way of checking if multiple $_POST parameters isset

I have these variables, and I need to check if all of them isset(). I feel there has to be a more efficient way of checking them rather than one at a time.
$jdmMethod = $_POST['jdmMethod'];
$cmdMethod = $_POST['cmdMethod'];
$vbsMethod = $_POST['vbsMethod'];
$blankPage = $_POST['blankPage'];
$facebook = $_POST['facebook'];
$tinychat = $_POST['tinychat'];
$runescape = $_POST['runescape'];
$fileUrl = escapeshellcmd($_POST['fileUrl']);
$redirectUrl = escapeshellcmd($_POST['redirectUrl']);
$fileName = escapeshellcmd($_POST['fileName']);
$appData = $_POST['appData'];
$tempData = $_POST['tempData'];
$userProfile = $_POST['userProfile'];
$userName = $_POST['userName'];
Try this
$allOk = true;
$checkVars = array('param', 'param2', …);
foreach($checkVars as $checkVar) {
if(!isset($_POST[$checkVar]) OR !$_POST[$checkVar]) {
$allOk = false;
// break; // if you wish to break the loop
}
}
if(!$allOk) {
// error handling here
}
I like to use a function like this:
// $k is the key
// $d is a default value if it's not set
// $filter is a call back function name for filtering
function check_post($k, $d = false, $filter = false){
$v = array_key_exists($_POST[$k]) ? $_POST[$k] : $d;
return $filter !== false ? call_user_func($filter,$v) : $v;
}
$keys = array("jdmMethod", array("fileUrl", "escapeshellcmd"));
$values = array();
foreach($keys as $k){
if(is_array($k)){
$values[$k[0]] = check_post($k[0],false,$k[1]);
}else{
$values[$k] = check_post($k[0]);
}
}
You could extend the keys array to contain a different default value for each post-value if you wish.
EDIT:
If you want to make sure all of these have a non-default value you could do something like:
if(sizeof(array_filter($values)) == sizeof($keys)){
// Not all of the values are set
}
Something like this:
$jdmMethod = isset($_POST['jdmMethod']) ? $_POST['jdmMethod'] : NULL;
It's Ternary Operator.
I think this should work (not tested, from memory)
function handleEmpty($a, $b) {
if ($b === null) {
return false;
} else {
return true;
}
array_reduce($_POST, "handleEmpty");
Not really. You could make a list of expected fields:
$expected = array(
'jdmMethod',
'cmdMethod',
'fileName'
); // etc...
... then loop those and make sure all the keys are in place.
$valid = true;
foreach ($expected as $ex) {
if (!array_key_exists($ex, $_POST)) {
$valid = false;
break;
}
$_POST[$ex] = sanitize($_POST[$ex]);
}
if (!$valid) {
// handle the problem
}
If you can develop a generic sanitize function, that will help - you can just sanitize each as you loop.
Another thing I like to use is function that gives a default as it sanitizes.
function checkParam($key = false, $default = null, $type = false) {
if ($key === false)
return $default;
$found_option = null;
if (array_key_exists($key,$_REQUEST))
$found_option = $_REQUEST[$key];
if (is_null($found_option))
$found_option = $default;
if ($type !== false) {
if ($type == 'string' && !is_string($found_option))
return $default;
if ($type == 'numeric' && !is_numeric($found_option))
return $default;
if ($type == 'object' && !is_object($found_option))
return $default;
if ($type == 'array' && !is_array($found_option))
return $default;
}
return sanitize($found_option);
}
When a default is possible, you'd not want to do a loop, but rather check for each independently:
$facebook = checkParam('facebook', 'no-facebook', 'string);
It is not the answer you are looking for, but no.
You can create an array an loop through that array to check for a value, but it doesn't get any better than that.
Example:
$postValues = array("appData","tempData",... etc);
foreach($postedValues as $postedValue){
if(isset($_POST[$postedValue])){
...
}
}

PHP loops to check that a set of numbers are consecutive

I'm trying to loop through a set of records, all of which have a "number" property. I am trying to check if there are 3 consecutive records, e.g 6, 7 and 8.
I think i'm almost there with the code below, have hit the wall though at the last stage - any help would be great!
$nums = array();
while (count($nums <= 3))
{
//run through entries (already in descending order by 'number'
foreach ($entries as $e)
{
//ignore if the number is already in the array, as duplicate numbers may exist
if (in_array($e->number, $num))
continue;
else
{
//store this number in the array
$num[] = $e->number;
}
//here i need to somehow check that the numbers stored are consecutive
}
}
function isConsecutive($array) {
return ((int)max($array)-(int)min($array) == (count($array)-1));
}
You can achieve the same result without looping, too.
If they just have to be consecutive, store a $last, and check to make sure $current == $last + 1.
If you're looking for n numbers that are consecutive, use the same, except also keep a counter of how many ones fulfilled that requirement.
$arr = Array(1,2,3,4,5,6,7,343,6543,234,23432,100,101,102,103,200,201,202,203,204);
for($i=0;$i<sizeof($arr);$i++)
{
if(isset($arr[$i+1]))
if($arr[$i]+1==$arr[$i+1])
{
if(isset($arr[$i+2]))
if($arr[$i]+2==$arr[$i+2])
{
if(isset($arr[$i+3]))
if($arr[$i]+3==$arr[$i+3])
{
echo 'I found it:',$arr[$i],'|',$arr[$i+1],'|',$arr[$i+2],'|',$arr[$i+3],'<br>';
}//if3
}//if 2
}//if 1
}
I haven't investigated it thoroughly, maybe can be improved to work faster!
This will confirm if all items of an array are consecutive either up or down.
You could update to return an array of [$up, $down] or another value instead if you need direction.
function areAllConsecutive($sequence)
{
$up = true;
$down = true;
foreach($sequence as $key => $item)
{
if($key > 0){
if(($item-1) != $prev) $up = false;
if(($item+1) != $prev) $down = false;
}
$prev = $item;
}
return $up || $down;
}
// areAllConsecutive([3,4,5,6]); // true
// areAllConsecutive([3,5,6,7]); // false
// areAllConsecutive([12,11,10,9]); // true
Here's an example that can check this requirement for a list of any size:
class MockNumber
{
public $number;
public function __construct($number)
{
$this->number = $number;
}
static public function IsListConsecutive(array $list)
{
$result = true;
foreach($list as $n)
{
if (isset($n_minus_one) && $n->number !== $n_minus_one->number + 1)
{
$result = false;
break;
}
$n_minus_one = $n;
}
return $result;
}
}
$list_consecutive = array(
new MockNumber(0)
,new MockNumber(1)
,new MockNumber(2)
,new MockNumber(3)
);
$list_not_consecutive = array(
new MockNumber(5)
,new MockNumber(1)
,new MockNumber(3)
,new MockNumber(2)
);
printf("list_consecutive %s consecutive\n", MockNumber::IsListConsecutive($list_consecutive) ? 'is' : 'is not');
// output: list_consecutive is consecutive
printf("list_not_consecutive %s consecutive\n", MockNumber::IsListConsecutive($list_not_consecutive) ? 'is' : 'is not');
// output: list_not_consecutive is not consecutive
If u don't wanna mess with any sorting, picking any of three numbers that are consecutive should give you:
- it either is adjacent to both the other numbers (diff1 = 1, diff2 = -1)
- the only number that is adjacent (diff = +-1) should comply the previous statement.
Test for the first condition. If it fails, test for the second one and under success, you've got your secuence; else the set doesn't comply.
Seems right to me. Hope it helps.
I think you need something like the following function (no need of arrays to store data)
<?php
function seqOfthree($entries) {
// entries has to be sorted descending on $e->number
$sequence = 0;
$lastNumber = 0;
foreach($entries as $e) {
if ($sequence==0 or ($e->number==$lastNumber-1)) {
$sequence--;
} else {
$sequence=1;
}
$lastNumber = $e->number;
if ($sequence ==3) {
// if you need the array of sequence you can obtain it easy
// return $records = range($lastNumber,$lastNumber+2);
return true;
}
}
// there isn't a sequence
return false;
}
function isConsecutive($array, $total_consecutive = 3, $consecutive_count = 1, $offset = 0) {
// if you run out of space, e.g. not enough array values left to full fill the required # of consecutive count
if ( $offset + ($total_consecutive - $consecutive_count ) > count($array) ) {
return false;
}
if ( $array[$offset] + 1 == $array[$offset + 1]) {
$consecutive_count+=1;
if ( $consecutive_count == $total_consecutive ) {
return true;
}
return isConsecutive($array, $total_consecutive, $consecutive_count, $offset+=1 );
} else {
return isConsecutive($array, $total_consecutive, 1, $offset+=1 );
}
}
The following function will return the index of the first of the consecutive elements, and false if none exist:
function findConsecutive(array $numbers)
{
for ($i = 0, $max = count($numbers) - 2; $i < $max; ++$i)
if ($numbers[$i] == $numbers[$i + 1] - 1 && $numbers[$i] == $numbers[$i + 2] - 2)
return $i;
return false;
}
Edit: This seemed to cause some confusion. Like strpos(), this function returns the position of the elements if any such exists. The position may be 0, which can evaluate to false. If you just need to see if they exist, then you can replace return $i; with return true;. You can also easily make it return the actual elements if you need to.
Edit 2: Fixed to actually find consecutive numbers.

Categories