2013-05-17 107 views
-1

連續兩個值我有一個多維數組PHP這樣檢查PHP數組

$array[0] = array('status' => 'Waiting' , 'number' => 10); 
$array[1] = array('status' => 'Missed' , 'number' => 20); 
$array[2] = array('status' => 'Waiting' , 'number' => 30); 
$array[3] = array('status' => 'Missed' , 'number' => 40); 
$array[4] = array('status' => 'Waiting' , 'number' => 50); 
$array[5] = array('status' => 'Waiting' , 'number' => 60); 
$array[6] = array('status' => 'Waiting' , 'number' => 70); 

我想要得到的$array[4]numbers$array[5],因爲他們之間沒有Missed。我怎樣才能做到這一點與PHP。什麼是簡單的方式?

輸出

50 and 60 
+0

5和6之間也沒有'錯過'。你想如何處理?你只想要第一個結果? –

+0

$ array [5]和$ array [6]怎麼樣?他們之間也沒有「錯過」。 –

+0

我只想要前兩個匹配的結果,並避免所有其他 –

回答

2
<?php 
$array[0] = array('status' => 'Waiting' , 'number' => 10); 
$array[1] = array('status' => 'Missed' , 'number' => 20); 
$array[2] = array('status' => 'Waiting' , 'number' => 30); 
$array[3] = array('status' => 'Missed' , 'number' => 40); 
$array[4] = array('status' => 'Waiting' , 'number' => 50); 
$array[5] = array('status' => 'Waiting' , 'number' => 60); 
$array[6] = array('status' => 'Waiting' , 'number' => 70); 
$last_status = ''; 
$last_number = ''; 
foreach($array as $foo){ 
    if($foo['status'] == $last_status && $last_status == 'Waiting'){ 
     echo "$last_number and $foo[number]"; 
     break; 
    } 
    $last_status = $foo['status']; 
    $last_number = $foo['number']; 
} 
?> 

Codepad example

+1

謝謝,這節省了我的大部分時間。我感謝您的幫助 –

0
for($i = 1; $i < count($array); $i++) { 
    if($array[$i - 1]['status'] == 'Waiting' && $array[$i]['status'] == 'Waiting') { 
     echo $array[$i - 1]['number'] . ' AND ' . $array[$i]['number']; 
     break; 
    } 
} 
0

另一種方式來做到這一點:

$array[0] = array('status' => 'Waiting' , 'number' => 10); 
$array[1] = array('status' => 'Missed' , 'number' => 20); 
$array[2] = array('status' => 'Waiting' , 'number' => 30); 
$array[3] = array('status' => 'Missed' , 'number' => 40); 
$array[4] = array('status' => 'Waiting' , 'number' => 50); 
$array[5] = array('status' => 'Waiting' , 'number' => 60); 
$array[6] = array('status' => 'Waiting' , 'number' => 70); 

array_walk(
     $array 
    , function ($value, $index, &$prev) { 
     if ($value['status'] == $prev['status'] && $prev['status'] == 'Waiting') { 
      echo $prev['number'] . ' AND ' . $value['number'] . PHP_EOL; 
     }  

     $prev = $value; 

    }, array(
      'status' => '' 
     , 'number' => 0 
    ) 
); 

See the demo