PHP: concatenate two arrays other than first key, second key

I have two arrays:

$array1 = array (a => '501', b => '1');
$array2 = array (a => '501', b => '2');

      

The combined array should look like this:

$merged_array = array (a => '501', b => '3');

      

I tried many suggestions, one of them is:

 $sums = array();
  foreach (array_keys($array1 + $array2) as $key) {
    $sums[$key] = (isset($array[$key]) ? $array[$key] : 0) + (isset($array2[$key]) ? $array2[$key] : 0);
  }

      

but this results in:

$merged_array = array (a => '1002', b => '3');

      

How should I do it? Any advice is greatly appreciated.

edit: After reading a few comments I realized I should have been clearer. below

4 arrays, notice the duplicates in 'a':

  $array1 = array (a => '501', b => '1');
  $array2 = array (a => '501', b => '2');
  $array3 = array (a => '505', b => '1');
  $array4 = array (a => '509', b => '1');

      

4 concatenated arrays and serialized should become something like

a:2:{s:1:"a";i:501;s:1:"b";i:3; s:1:"a";i:505;s:1:"b";i:1; s:1:"a";i:509;s:1:"b";i:1;}

      

so: 2x a => '501' becomes 1x a => '501' and the keys 'b' become "3" (summed up)

and: 1x a => '505' and b => '1'

and: 1x a => '509' and b => '1'

+3


source to share


2 answers


You can build an array with key "a" as key and value "b" as value

function map_a_to_b($array) {
    return array($array['a'] => $array['b'];
}

      

Apply map_a_to_b

to all input arrays. Then you can concatenate the arrays recursively:

$merged = array_merge_recursive($array1, $array2, $array3, $array4);

      

The result will be (for your example):



  array ('501' => array('1', '2'),
         '505' => '1',
         '509' => '1')

      

Now let's summarize the internal arrays as follows:

$summed = array_map(function($item) { return array_sum((array) $item); }, $merged);

      

And convert your array of key values ​​to a / b structure. I don't know exactly what it should look like because I cannot read serialized arrays fluently. Therefore, if you need help with this, please show the desired result as an unserialized array.

+1


source


$array1 = array (a => '501', b => '1');
$array2 = array (a => '501', b => '2');

function super_merge($a1, $a2)
{
  $a = array();
  $k_ar = array_keys($a1 + $a2);

  foreach ($k_ar as $k)
  {
    if (isset($a1[$k]) && isset($a2[$k]) && $a1[$k] == $a2[$k])
      $a[$k] = $a1[$k];
    else
      $a[$k] = (isset($a1[$k]) ? $a1[$k] : 0) + (isset($a2[$k]) ? $a2[$k] : 0);
  }

  return $a;
}

var_dump(super_merge($array1, $array2));

      



+3


source







All Articles