Php数组多维关联比较值

时间:2016-03-01 18:13:21

标签: php foreach

嗨我有这样的结构数组。我想比较循环这样的条件。

if(dataInto[0]>=MyDataTypeFromInput && dataOut[0]<=MyDataTypeFromInput && room[0]==MyIdRoom) {...}

而不是索引0,这必须在循环foreach中工作。因此,将index [0]与index [0] [1]与[1]等进行比较

这是怎么回事?

[
'dataInto' => [
    0 => '2016-07-14 14:50'
    1 => '2016-03-24 14:00'
    2 => '2016-03-03 06:30'
]
'room' => [
    0 => 13
    1 => 14
    2 => 14
]
'dataOut' => [
    0 => '2016-07-14 18:10'
    1 => '2016-03-24 17:20'
    2 => '2016-03-03 09:50'
   ]
]

2 个答案:

答案 0 :(得分:1)

只需根据主数组项之一的长度执行foreach循环:

foreach( $array['dataInto'] as $key => $val )
{
    if
    (
        $array['dataInto'][$key] >= MyDataTypeFromInput 
        && 
        $array['dataOut'][$key]  <= MyDataTypeFromInput 
        && 
        $array['room'][$key]     == MyIdRoom
    )
    {
    ...
    }
}

答案 1 :(得分:1)

我不会在foreach循环中执行此操作,更合理的方法是使用for循环,因为所有索引都是数字。

for($i = 0; $i < count($arr['dataInto']); $i++){
  if($arr['dataInto'][$i] >= MyDataTypeFromInput
  && $arr['dataOut'][$i]  <= MyDataTypeFromInput
  && $arr['room'][$i]     == MyIdRoom){
    // etc..
  }
}

但是,如果你想循环主数组,那么foreach循环就是有序的。

foreach($arr as $key => $value){ 
  echo $key, ', '; // ouput: "dataInto, dataOut, room" 
  foreach($value as $subkey => $subvalue){
    echo $subkey, ' -> ', $subvalue; // will first loop dataInto and display all 3 values with numeric keys 0, 1, 2.
  }
}
相关问题