如何合并具有相同键值的数组

时间:2018-04-19 08:42:59

标签: php arrays

如何合并下面的数组,我想通过province_code合并tax_year

Original Array

我怎样才能把它变成这个

Target Array

请建议我。谢谢(抱歉,我无法粘贴我的代码)

语言 PHP

以下是文本版本https:// pastebin.com/FSnUR1je

我想合并数组取决于省代码

2 个答案:

答案 0 :(得分:0)

我会创建一个关联索引:

$index = array();
foreach ($data as $v) {
    $indexkey = $v["province_code"];
    if (isset($index[$indexkey])) {
        $entry = $index[$indexkey]; // key already exists, will merge
    } else {
        $entry = array(
            "province" => $v["province"],
            "province_code" => $v["pronvince_code"]
        ); // key does not exist, create new and then merge
    }

    // merge here data
    $entry["total_" . $v["tax_year"]] = $v["total"];
    // ...

    // write entry back to the index
    $index[$indexkey] = $entry;
}

最后,您可以将其转换回带有foreach和array_push的数字索引数组,或保持原样。

答案 1 :(得分:0)

最有可能是比这更好的解决方案,但这对您有用

输入

<?php
$data["0"]=["province_code"=>"1","province"=>"VT","total"=>1009,"total_amount"=>123456,"tax_year"=>"2018"];
$data["1"]=["province_code"=>"1","province"=>"VT","total"=>453,"total_amount"=>123456,"tax_year"=>"2017"];
$data["2"]=["province_code"=>"5","province"=>"SV","total"=>85,"total_amount"=>56789,"tax_year"=>"2018"];
$data["3"]=["province_code"=>"5","province"=>"SV","total"=>54,"total_amount"=>56789,"tax_year"=>"2017"];

$data2=[];
$codes=[];
foreach($data as $k=>$v){
    if(isset($codes[$v['province_code']])) $k=$codes[$v['province_code']];
    else $codes[$v['province_code']]=$k;
    $data2[$k]['province_code']=$v['province_code'];
    $data2[$k]['province']=$v['province'];
    $data2[$k]['total_'.$v['tax_year']]=$v['total'];
    $data2[$k]['total_amount_'.$v['tax_year']]=$v['total_amount'];
}

echo "<h2><pre>";
print_r($data2);
?>

输出

Array
(
    [0] => Array
        (
            [province_code] => 1
            [province] => VT
            [total_2018] => 1009
            [total_amount_2018] => 123456
            [total_2017] => 453
            [total_amount_2017] => 123456
        )

    [2] => Array
        (
            [province_code] => 5
            [province] => SV
            [total_2018] => 85
            [total_amount_2018] => 56789
            [total_2017] => 54
            [total_amount_2017] => 56789
        )

)