简体   繁体   中英

checking array with previous value in array

I have an time array and the frequency of reading is 5 seconds

I want to check if the frequency of reading is 5 second between every element of

array

My code

$freq_of_reading = 5;
$res_arr = array(
    0 => array("13:53:45"),
    1 => array("13:53:50"),
    2 => array("13:53:55"),
    3 => array("13:54:00"),
    4 => array("13:54:05"),
    5 => array("13:54:10"),
    6 => array("13:54:15"),
    7 => array("13:54:20"),
    8 => array("13:54:25"),
    9 => array("13:54:30"),
);


try {
    $u = 0;
    foreach ($res_arr as $key => $item) {
        // if(strtotime($item))
        //Logic here 
    }
} catch (Exception $e) {
    echo $exp = $e->getMessage();
}

Try this loop:

for($i = 0; $i < count($res_arr) - 1; $i++)
{
    if(strtotime($res_arr[$i + 1][0]) - strtotime($res_arr[$i][0]) != $freq_of_reading)
    {
        echo "Element $i differs from the next one more than $freq_of_reading s";
        exit;
    }    
}

try this code

$count = count($res_arr);
for($i=0;$i<$count$i++)
    {
        $number = intval(substr($res_arr[$i], -2));

        $number1 = substr(($res_arr[$i+1], -2));
        if(($number1-$number) == 5)
        {
          echo "true";
        }

    }

Not sure why that's in a try , but:

$freq_of_reading = 5;
$previous = 0;

foreach($res_arr as $item) {
    $time = strtotime($item[0]);
    if($time - $freq_of_reading == $previous) {
        echo 'yes';
    }
    $previous = $time;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM