根据另一个数组中的值更改数组中的值

时间:2014-03-28 06:15:10

标签: php arrays

这是一个简单的英语示例,我想要实现的目标: 如果给定的数字是4,那么我想将每个等于或小于4的值加1到另一个数组的相应索引中。 (希望有道理)

所以我的第一个数组看起来像这样:

Array ( [0] => 5 [1] => 6 [2] => 7 [3] => 4 [4] => 3 [5] => 2 [6] => 9 [7] => 8 [8] => 1 [9] => 10 [10] => 11 [11] => 12 [12] => 13 [13] => 14 [14] => 15 [15] => 16 [16] => 17 [17] => 18 ) 

第二个数组如下所示:

Array ( [0] => 4 [1] => 3 [2] => 4 [3] => 4 [4] => 4 [5] => 5 [6] => 4 [7] => 4 [8] => 5 [9] => 4 [10] => 4 [11] => 5 [12] => 5 [13] => 4 [14] => 4 [15] => 4 [16] => 3 [17] => 3 ) 

我希望第二个数组看起来像这样(在第一个数组中为每个低于4的值加1后),所以在添加后它将是

Array ( [0] => 4 [1] => 3 [2] => 4 [3] => 5 [4] => 5 [5] => 6 [6] => 4 [7] => 4 [8] => 6 [9] => 4 [10] => 4 [11] => 5 [12] => 5 [13] => 4 [14] => 4 [15] => 4 [16] => 3 [17] => 3 ) 

在哪个指数3,4,5,9已经改变。

2 个答案:

答案 0 :(得分:3)

我认为您正在寻找array_map

function increase( $m, $n )
{
  if( $m < 4 )
  {
   return $n+1;
  }
  return $n
}

$arr1;
$arr2;

print_r( array_map("increase", $arr1, $arr2 ) );

注意:这将返回一个新数组。

答案 1 :(得分:1)

使用array_walk

array_walk($arr2,function(&$v,$k) use($arr1) { if($arr1[$k]<=$v){ $v=$v+1;} });

Demo

[或]

简单foreach即可

foreach($arr1 as $k=>$v)
{
    if($v<=$arr2[$k])
    {
        $arr2[$k]=$arr2[$k]+1;
    }
}
print_r($arr2);

Demo