使用PHP组合多个数组

时间:2016-06-21 08:37:42

标签: php arrays

我想通过添加重复值将两个数组合并为单个数组,例如

$first = array('one','two','one');
$second = array(10,5,30);

预期结果将是,

$third = array(

       'one' => 40,
       'two' => 5
           );

这里我添加了两个对应重复位置的数字。

提前致谢!

4 个答案:

答案 0 :(得分:1)

尝试

$first = array('one','two','one');
$second = array(10,5,30);

$third  = array();
foreach ($first as $f_k=>$f_v)
{
    if(isset($new_array[$f_v]))
        $third[$f_v] +=$second[$f_k];
    else
        $third[$f_v] = $second[$f_k];
}
print_r($third);

答案 1 :(得分:1)

创建一个新数组并插入第一个值作为键,第二个作为值插入,也可以在重复时添加。

Working demo

$first = array('one','two','one');
$second = array(10,5,30);

$third = array();
foreach($first as $k => $v){
    if(isset($third[$v]))
        $third[$v] += $second[$k];
    else
        $third[$v] = $second[$k];
}
print_r($third);

答案 2 :(得分:1)

使用array_walk函数的简单解决方案:

$result = [];
array_walk($first, function($v, $k) use(&$result, $second){
    $result[$v] = (isset($result[$v]))? ($result[$v] + $second[$k]) : $second[$k];
});

print_r($result);

输出:

Array
(
    [one] => 40
    [two] => 5
)

答案 3 :(得分:0)

  Simple and working code
   <?php
      $first = array('one','two','one');
      $second = array(10,5,30);
      $result = array_combine_($first ,$second );
      echo $result;
     function array_combine_($keys, $values)
     {
       $result = array();
       foreach ($keys as $i => $k) {
            $result[$k][] = $values[$i];
       }
       $result = myfunction($result);
       return    $result;
      } 

      function myfunction($result)
      {
        foreach($result as $key=>$value)
        {
          if(is_array($value))
          {
               $new_array[$key] = array_sum($value);
          }
          else
          {
              $new_array[$key] = $value;
          }
        }   
      return    $new_array;
    }
 ?>