我有一个像这样的多维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);
我希望得到numbers
$array[4]
和$array[5]
,因为它们之间没有Missed
。我怎么能用PHP做到这一点。什么是简单的方式?
输出
50 and 60
答案 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;
}
}
答案 2 :(得分: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
)
);