比较基于数组先前值的数组

时间:2015-11-06 10:26:55

标签: php arrays

我有一个如下所示的数组:

Array ( 
    [0] => Array (  
        [START] => COI-COK 
        [RETURN] => CAI - DEL 
    ) 
    [1] => Array ( 
        [START] => COK - AMM 
        [RETURN] => CAI - DEL 
    ) 
)

我想检查previous和current数组的'start'和'end'值是否相同。如果没有,则打印一些值。我该怎么办?

这是我的尝试:

foreach($data as $datas)
{     
    $old_start  = $datas['START'];
    $old_return = $datas['RETURN'];

    ...

    if( ($old_start == $datas['START']) && ($old_return == $datas['RETURN']))
    {

    }
    else
    {

    }
}

但它不起作用,因为所有时间old_start值都等于$datas['START']

print_r($data)显示此输出:

Array ( 
    [0] => Array ( 
        [Sl] => 2 
        [TRAVELDAY] => 2015-11-11 
        [RETURNDAY] => 2015-11-27 
        [START] => COI-COK 
        [RETURN] => CAI - DEL 
    ) 
    [1] => Array ( 
        [Sl] => 1 
        [TRAVELDAY] => 2015-11-11 
        [RETURNDAY] => 2015-11-27 
        [START] => COK - AMM 
        [RETURN] => CAI - DEL 
    ) 
)

4 个答案:

答案 0 :(得分:2)

您必须在比较之后而不是之前进行分配:

$old_start = '';
$old_return = '';
foreach($data as $datas)
{     
     //....
     if($old_start=='' || $old_start == $datas['START'] && $old_return == $datas['RETURN'])
     {
         //....
     }
     else
     {
         //code to be executed
     }

     $old_start = $datas['START'];
     $old_return = $datas['RETURN'];
}

答案 1 :(得分:1)

else
{
    base.OnActionExecuting(filterContext);
}

答案 2 :(得分:1)

试试这样..

$old_start = "";
$old_return = "";

foreach($data as $datas)
{     

    if( ($old_start == $datas['START']) && ($old_return == $datas['RETURN']))
    {
        //true code to be executed
    }
    else
    {
        //false code to be executed
    }

    $old_start = $datas['START'];
    $old_return = $datas['RETURN'];
}

答案 3 :(得分:0)

$tot=number_format( $ser->sum / ( $tch * 100 ), 2 );
$alt_tot=number_format( ( $ser->sum / $tch ) * 100, 2 );

希望这会清除你的逻辑,添加你想要的数组值,我将你的数组从2修改为3以显示差异。这将比较n与n + 1并显示结果。