Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/254.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP唯一/求和/合并数组操作_Php_Arrays_Merge_Unique - Fatal编程技术网

PHP唯一/求和/合并数组操作

PHP唯一/求和/合并数组操作,php,arrays,merge,unique,Php,Arrays,Merge,Unique,这很难用文字来解释,但基本上我需要取两个数组,用唯一的值合并它们,并对其中一列求和。如果写在下面,它更有意义: $a = array( 0 => array( 'ID' => 1, 'Count' => 2 ), ); $b = array( 0 => array( 'ID' => 1, 'Count' => 4, ), 1 => array( 'ID' =>

这很难用文字来解释,但基本上我需要取两个数组,用唯一的值合并它们,并对其中一列求和。如果写在下面,它更有意义:

$a = array(
   0 => array(
      'ID' => 1,
      'Count' => 2
   ),
);

$b = array(
   0 => array(
      'ID' => 1,
      'Count' => 4,
   ),
   1 => array(
      'ID' => 2,
      'Count' => 3,
   ),
);
我需要的最终产品是:

$a_plus_b = array(
    0 => array(
       'ID' => 1,
       'Count' => 6,
    ),
    1 => array(
       'ID' => 2,
       'Count' => 3,
    ),        
);

我一直在玩不同版本的array_merge()和array_unique(),但我找不到一个有效的方法来做我需要的事情。我知道我总是可以做嵌套循环,但我希望做一些更简单的事情。有什么想法吗?

这应该就行了

注意:此解决方案需要PHP
=5.3
。下面有一个PHP<5.3的解决方案

$input = array($a, $b);
// add as many result arrays to $input as you want; e.g.,
// $input = array($a, $b, $c, $d);

$output = array_count_values(
  call_user_func_array(
    'array_merge',
     array_map(
       function($arr) {
         return array_fill(0, $arr['Count'], $arr['ID']);
       },
       call_user_func_array(
         'array_merge',
         $input
       )
     )
  )
);

print_r($output);
输出

数组
(
[1] => 6
[2] => 3
)
注意上面的数组键是
ID
值。数组值是
Count


如果您运行的是PHP
<5.2
,则无法将内联闭包与
array\u fill
一起使用。您必须将其定义为一个单独的函数

$input = array($a, $b);

function _fill($arr) {
  return array_fill(0, $arr['Count'], $arr['ID']);
}

$output = array_count_values(
  call_user_func_array(
    'array_merge',
    array_map(
      '_fill',
      call_user_func_array(
        'array_merge',
        $input
      )
    )
  )
);

print_r($output);

从这里开始,将输出转换为所需的格式是一项简单的任务