-2

Is it possible to merge the contents of all existing arrays, if the key is already in use - then nothing, and if not - then it must be added from other arrays, but with an empty value

  array(3) {
      [0]=>
            array(4) {
              ["attributes_3_ru-ru"] => "10"
              ["attributes_3_en-gb"] => "100"
              ["attributes_4_en-gb"] => "2222"
              ["attributes_4_ru-ru"] => ""
            }
      [1]=>
            array(2) {
              ["attributes_6_ru-ru"] => "10"
              ["attributes_6_en-gb"] => "100"
            }
        }
      [2]=>
            array(2) {
              ["attributes_4_ru-ru"] => "10"
              ["attributes_4_en-gb"] => "100"
            }
            ...n
    }

output is something like this

array(3) {
  [0]=>
        array(4) {
          ["attributes_3_ru-ru"] => "10"
          ["attributes_3_en-gb"] => "100"
          ["attributes_4_en-gb"] => "2222"
          ["attributes_4_ru-ru"] => ""
          ["attributes_6_ru-ru"] => ""
          ["attributes_6_en-gb"] => ""
        }
  [1]=>
        array(2) {
          ["attributes_6_ru-ru"] => "10"
          ["attributes_6_en-gb"] => "100"
          ["attributes_3_ru-ru"] => ""
          ["attributes_3_en-gb"] => ""
          ["attributes_4_en-gb"] => ""
          ["attributes_4_ru-ru"] => ""
        }
    }
  [2]=>
        array(2) {
          ["attributes_4_ru-ru"] => "10"
          ["attributes_4_en-gb"] => "100"
          ["attributes_6_ru-ru"] => ""
          ["attributes_6_en-gb"] => ""
          ["attributes_3_ru-ru"] => ""
          ["attributes_3_en-gb"] => ""
        }
        ...n
    }

2 Answers2

2

I would do it like this. First, collect all the keys and create a "template" array with from that with blank values.

$merged = array_merge(...$arrays);
$template = array_fill_keys(array_keys($merged), '');

Then map that over the original array of arrays and merge each entry with the template.

$result = array_map(function($entry) use ($template) {
    return array_merge($template, $entry);
}, $arrays);
Don't Panic
  • 39,820
  • 10
  • 58
  • 75
0

You should use array_merge() for this.

$megaArray = array_merge($array1, $array2, $array3);

Or if I'm oversimplifying your use case and for some reason you need to append data to $array3 you could use foreach() and in_array() instead. Something along the lines of the following (not tested).

foreach($array1 as $key => $value){
    if(!in_array($key, $array3)){
        $array3[$key] = $value;
  }
  else{
        if($array3[$key] === ""){ // if the current array3 iteration's value is blank, use the new one
            $array3[$key] = $value;
        }
  }
}
Luke
  • 11
  • 3