PHP,如果数组键具有任何值,则之前所有值+1

时间:2018-06-23 11:06:49

标签: php

$a = array(1,0,0,1,2,0,0,6);

在上面的数组中,如果键值不为null,则需要为所有先前的键值加+1。

[0]=>1 => +1 = 2 => +1 = 3 => +1 = 4
[1]=>0 => +1 = 1 => +1 = 2 => +1 = 3
[2]=>0 => +1 = 1 => +1 = 2 => +1 = 3
[3]=>1  ( here 3rd key have value so now all previous value +1 ) +1 = 2 => +1 = 3
[4]=> 2 ( again 4th key have value so now all previous value +1 ) +1 = 3
[5] => 0 => +1 = 1
[6] => 0 => +1 = 1
[7] => 6 ( again 7th key have value so now all previous value +1 ) 

请帮助我解决这个问题。

1 个答案:

答案 0 :(得分:0)

这是逻辑

 $a = array(1,0,0,1,2,0,0,6);
 $b = [];
 foreach( $a as $key => $value){
   array_push($b , $key);
   if($value > 0 AND $key>0 ){
     for( $i = 0 ; $i < count($b)-1 ; $i++ ){
        ++$a[$b[$i]];
     }
   }
 }
print_r($a);

希望获得帮助。