PHP7:组合两个数组,其中一个是键,第二个是值(整数),重复键的和值

时间:2017-10-10 16:07:18

标签: php sum duplicates php-7 array-merge

我在PHP7中有2个数组:

$Array1 = ["bus","bus","int"];
$Array2 = [2,18,10];

其中$ Array1为 key ,$ Array2为每个索引值。 我需要将重复键的两个值和和值组合在一起,例如:得到以下输出:

$Array3 = ["bus" => 20, "int" => 10];

谢谢!

3 个答案:

答案 0 :(得分:2)

您需要的代码就像这样简单:

m

其输出:

// The input arrays
$Array1 = ['bus', 'bus', 'int'];
$Array2 = [2, 18, 10];

// Build the result here
$Array3 = [];

// There is no validation, the code assumes that $Array2 contains
// the same number of items as $Array1 or more
foreach ($Array1 as $index => $key) {
    // If the key $key was not encountered yet then add it to the result
    if (! array_key_exists($key, $Array3)) {
        $Array3[$key] = 0;
    }

    // Add the value associate with $key to the sum in the results array
    $Array3[$key] += $Array2[$index];
}

print_r($Array3);

答案 1 :(得分:0)

这个可行:

$Array1 = ['bus', 'bus', 'int'];
$Array2 = [2, 18, 10];

# Let $Array3 be the required results array.
 $Array3 = [];
 for($j = 0; $j < count($Array1); $j += 1){
  $k = $Array1[$j];
  /*If the key already exists in $Array3 , add to it the value in the present key, 
   else just enter it as a new element. */
 if(array_key_exists($k,$Array3)){ $Array3[$k] = $Array3[$k] + $Array2[$j];}
   else { 
# But first check that the length of $Array2 is not exceeded
   if($j <= count($Array2)){
    $Array3[$k] = $Array2[$j];
          }
       }
 }

 print_r($Array3);

        # gives: Array ( [bus] => 20 [int] => 10 ) 

答案 2 :(得分:-1)

我会成功的。我希望它对你有所帮助:你可以通过使用额外的阵列来获得所需的输出,首先,计算你的数组元素,这将是你的条件。这个简单的检查

$Array1[$x] == $Array1[$x+1]

将检查数组连续地址是否具有相同的值。 (条件必须对数组进行排序),

和另一个这样的值:

 $arr[$Array1[$x]] // assign a key

这是为了使它关联数组:

$Array1 = ["bus","bus","int"];
$Array2 = [2,18,10];

$arr = [];

for ($x = 0; $x < count($Array1); $x++) {
  if($Array1[$x] == $Array1[$x+1])
    {
      $arr[$Array1[$x]] = $Array2[$x] + $Array2[$x+1]; 
      $x++;
    }
  else
    {
     $arr[$Array1[$x]] = $Array2[$x];
    }

}

输出是:

Array ( [bus] => 20 [int] => 10 )