在给定的数组中,我想找到第一个从该键获得零值的键,直到数组结束。例如:
$data1 = array(
'1 Jan|8:30' => '12.6',
'2 Feb|8:30' => '250',
'3 Mar|8:10' => '0',
'4 Apr|23:30' => '7',
'5 Apr|23:30' => '80',
'6 Apr|23:30' => '67',
'7 r|23:30' => '0',
'8 Ap|23:30' => '0',
'9 Lr|23:30' => '0',
'10 Apr|23:30' => '0'
);
// outcome should: be '7 r|23:30' => '0'
和
$data2 = array(
'1 Jan|8:30' => '12.6',
'2 Feb|8:30' => '250',
'3 Mar|8:10' => '0',
'4 Apr|23:30' => '7',
'5 Apr|23:30' => '80',
'6 Apr|23:30' => '67',
'7 r|23:30' => '0',
'8 Ap|23:30' => '0',
'9 Lr|23:30' => '1',
'10 Apr|23:30' => '0'
);
// outcome should be: '10 Apr|23:30' => '0'
答案 0 :(得分:1)
您可以向后迭代数组,直到值不再是'0'
:
$key = null;
for ($value = end($arr); $value !== false && $value == '0'; $value = prev($arr)) {
$key = key($arr); // keep track of current key
}
if ($key !== null) {
echo $key, ' = ', $arr[$key];
}