Home > database >  Merge 2 arrays with refernce to key and add thier values using php
Merge 2 arrays with refernce to key and add thier values using php

Time:12-22

I'm trying to merge multiple arrays with same keys and add their values if keys exist, if not add a new object. Could not get the logic right on this

these are samle arrays

[{"2":"90"},{"12":"400"},{"25":"750"},{"0":"50"}] 
[{"1":"100"},{"23":"200"},{"12":"1000"},{"0":"5"}]

and the expected output is

[{ {"2":"90"},{"12":"1400"},{"25":"750"},{"0":"55"},{"1":"100"},{"23":"200"}]

This is php code i have used

 while($row = $result->fetch_assoc()) 
      {
          
             if ($i==0)
             {
                 $rowOut = $row;
                 $i  ;
             }else
             {
                    foreach($rowOut as $key1 => $value1) {
                        
                        foreach($row as $key => $value) 
                        {
                        
                            if($key == $key1){
                                
                                 (int)$rowOut->$value1 = (int)$value   (int)$value1;
                            }
                            
                        }
                    }  
             }
         
        }

CodePudding user response:

not the most elegant solution, but it works

$a = [2=>90,12=>400,25=>750,0=>50] ;
$b = [1=>100,23=>200,12=>1000,0=>5];
$ak = array_keys($a);
$bk = array_keys($b);
$ck = array_intersect($ak,$bk);
$out = [];
foreach ($ck as $key => $value)
{
    $out[$value] = $a[$value]   $b[$value];
    unset($a[$value]);
    unset($b[$value]);
}

foreach ($a as $key => $value)
{
    $out[$key] = $value;
}

foreach ($b as $key => $value)
{
    $out[$key] = $value;
}

var_dump($out);

CodePudding user response:

You may concat the two arrays and use reduce to construct the new array.

demo

<?php
$array1 = [
    ["2" => "90"],
    ["12" => "400"],
    ["25" => "750"],
    ["0" => "50"]
];

$array2 = [
    ["1" => "100"],
    ["23" => "200"],
    ["12" => "1000"],
    ["0" => "5"]
];

$concat = [...$array1, ...$array2];

$reduce = array_reduce($concat, function ($carry, $item) {
    $key = array_keys($item)[0];

    if (isset($carry[$key])) {
        $carry[$key][$key]  = $item[$key];
    } else {
        $carry[$key] = [$key => $item[$key]];
    }
    $carry[$key][$key] = (string)$carry[$key][$key];
    return $carry;
}, []);

$output = array_values($reduce);

echo var_dump($output);
  •  Tags:  
  • php
  • Related