将0替换为数组中的下一个非零元素

时间:2014-02-10 11:40:03

标签: php arrays

我有以下数组:

Array
(
[0] =>Array(
    [total_users]=>101
)
[1] =>Array(
    [total_users]=>100
)
[2] =>Array(
    [total_users]=>0
)
[3] =>Array(
    [total_users]=>0
)
[4] =>Array(
    [total_users]=>88
)
[5] =>Array(
    [total_users]=>78
)
[6] =>Array(
    [total_users]=>0
)
[7] =>Array(
    [total_users]=>56
)

)

现在我需要的是我需要在foreach循环中用下一个非零值替换零值。我的意思是我需要在索引2和3上获得88,因为它是下一个非零值。同样在dex 6中我需要56.我该怎么做?

3 个答案:

答案 0 :(得分:1)

试试这个

   $arr_length = sizeof($your_array);  
$pre_val = 0;     
for($i=arr_length-1; $i>=0; $i--)
{
    if($your_array[$i]['total_users']==0)
    {
        $your_array[$i]['total_users'] = $pre_val;
    }
    else
    {
        $pre_val = $your_array[$i]['total_users'];
    }   

}   

print_r($your_array);

答案 1 :(得分:0)

你可能会向后循环数组。

保持变量的最后一个非零值,当遇到零时,将其替换为数组中的该值。

答案 2 :(得分:0)

你可以向后循环数组:

<?php
    $array = array(
        array('total_users' => 101),
        array('total_users' => 100),
        array('total_users' =>   0),
        array('total_users' =>   0),
        array('total_users' =>  88),
        array('total_users' =>  78),
        array('total_users' =>   0),
        array('total_users' =>  56)
    );

    for ($i = count($array) - 2; $i >= 0; $i--) {
        if ($array[$i]['total_users'] == 0) {
            $array[$i]['total_users'] = $array[$i + 1]['total_users'];
        }
    }

    print_r($array);
?>

输出:

Array
(
    [0] => Array( [total_users] => 101 )
    [1] => Array( [total_users] => 100 )
    [2] => Array( [total_users] =>  88 )
    [3] => Array( [total_users] =>  88 )
    [4] => Array( [total_users] =>  88 )
    [5] => Array( [total_users] =>  78 )
    [6] => Array( [total_users] =>  56 )
    [7] => Array( [total_users] =>  56 )
)

DEMO