0

在给定的数组中,我想找到从该键到数组末尾具有零值的第一个键。例如:

$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'
4

1 回答 1

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];
}
于 2013-02-27T07:53:40.467 回答