合并数组中的数组并添加值

时间:2020-05-08 22:07:46

标签: php arrays

我需要一个像这样的数组:

Array
(
    [0] => Array
        (
            [county_code] => 54045
            [count] => 218
        )

    [1] => Array
        (
            [county_code] => 54045
            [count] => 115
        )

    [2] => Array
        (
            [county_code] => 54051
            [count] => 79
        )

)

并使用相同的county_code合并所有数组并添加计数,如下所示:

Array
(
    [0] => Array
        (
            [county_code] => 54045
            [count] => 333
        )

    [1] => Array
        (
            [county_code] => 54051
            [count] => 79
        )

)

会有多个县代码的多个实例。

有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:0)

如所承诺的:

<?php
$initial_array = [
    ['country_code' => 54045, 'count' => 218],
    ['country_code' => 54045, 'count' => 115],
    ['country_code' => 54051, 'count' => 79],
];

$synth = [];
foreach ($initial_array as $sa) { # $sa: subarray
  if (!isset($synth[$sa['country_code']])) {
    $synth[$sa['country_code']] = 0;
  }
  $synth[$sa['country_code']] += $sa['count'];
}
print_r($synth); # Synthesis array: keys are country codes, values are cumulative counts.

# If you need the same format for both the initial and synthesis arrays, then continue with this:
$synth2 = [];
foreach ($synth as $k => $v) {
  $synth2[] = ['country_code' => $k, 'count' => $v];
}
print_r($synth2);
?>

此代码的小提琴:https://3v4l.org/M8tkb

最诚挚的问候

答案 1 :(得分:0)

尝试一下:

// your example array
$array = [
    [
        "county_code" => 54045,
        "count" => 218
    ],
    [
        "county_code" => 54045,
        "count" => 115
    ],
    [
        "county_code" => 54051,
        "count" => 79
    ]
];

// intrim step to collect the count.
$intrimArray = [];        
foreach( $array as $data ){
    $countyCode = $data["county_code"];
    if (!$intrimArray[$countyCode]) {
        $intrimArray[$countyCode] = $data["count"];
    } else {
        $intrimArray[$countyCode] = $intrimArray[$countyCode] + $data["count"];
    }
}

// build the final desired array using interim array.
$finalArray = [];
foreach($intrimArray as $countyCode => $totalCount) {
    array_push($finalArray, [
        "county_code" => $countyCode,
        "count" => $totalCount
    ]);
}

var_dump($finalArray);
相关问题