如何从整数定义数组值?

时间:2016-05-11 23:16:41

标签: php arrays

好的,下面我附上了我的代码,我正在尝试使用$current_statement$next_statement来定义数组中的值。 $current_statement是=到7而$next_statement是=到8.我要做的是使用{{1}中的两个值来定义数组中的第7和第8个值}和$current_statement

$next_statement

示例

我正在尝试使用 <? $date = array('16-01-14','16-01-28','16-02-14','16-02-28','16-03-14','16-03-28', '16-04-14','16-04-28','16-05-14','16-05-28','16-06-14','16-06-28','16-07-14', '16-07-28','16-08-14','16-08-28','16-09-14','16-09-28','16-10-14','16-10-28', '16-11-14','16-11-28','16-12-14','16-12-28'); $currentdate = date('y-m-d'); foreach ($date as $i => $d) { if ($currentdate >= $d && ($i == count($date)-1 || $currentdate < $date[$i+1])) { $current_statement = $i; $next_statement = $i+1; } } ?> $current_statement中的两个数值来从数组中选择值。因此,例如,如果$next_statement = = 7,它将从数组中选择第7个值并将其定义为单独的变量。如果$current_statement = = 8,它将从数组中选择第8个值并将其定义为单独的变量。所以我可以很容易地回应这两个变量。

2 个答案:

答案 0 :(得分:2)

我对你的要求并不完全清楚,所以这个答案有点猜测,当然我不应该这样做。但你的意思是这样吗

<?php
    $date = array('16-01-14','16-01-28','16-02-14','16-02-28','16-03-14',
                  '16-03-28','16-04-14','16-04-28','16-05-14','16-05-28',
                  '16-06-14','16-06-28','16-07-14', '16-07-28','16-08-14',
                  '16-08-28','16-09-14','16-09-28','16-10-14','16-10-28',
                  '16-11-14','16-11-28','16-12-14','16-12-28');    

    $currentdate = date('y-m-d');

    foreach ($date as $i => $d) {
        if ($currentdate >= $d && ($i == count($date)-1 || $currentdate < $date[$i+1])) {
            echo 'Current statement date = ' . $date[$i];
            echo 'Next statement date = ' . $date[$i+1];
        } 
    }
?>

在这种情况下,您不需要创建的2个变量,只需使用$i$i+1

答案 1 :(得分:0)

我认为您需要阻止索引超出绑定异常:

$current_statement  = false;
$next_statement     = false;
foreach ($date as $i => $d) 
{
    if ($id<count($date)-1 && ($currentdate >= $d && ($i == count($date)-1 || $currentdate < $date[$i+1]))) 
    {
        $current_statement  = $i;
        $next_statement     = $i+1;
    } 
}
if($current_statement)
{
    $current_date   = $date[$current_statement];
    $next_date      = $date[$next_statement];
}

不久之后,如果您不再需要$ current_statement和$ next_statement变量:

foreach ($date as $i => $d) 
{
    if ($id<count($date)-1 && ($currentdate >= $d && ($i == count($date)-1 || $currentdate < $date[$i+1]))) 
    {
        $current_date   = $date[$i];
        $next_date      = $date[$i + 1];
    } 
}

忘掉这个答案
你正在阻止这个问题:$ i == count($ date)-1