rorymorris89 rorymorris89 - 5 months ago 15
PHP Question

Merge array with varying key value pairs

So I have various arrays which do not always have the same key/value pairs in them. What I want to do is to be able to merge the arrays, but to add in empty key/value pairs if they don't already exist in that array, but do in others. It's hard to explain but this might explain it better:

$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');


I need to somehow turn this into:

$finalArray = array(
array('name' => 'rory', 'car' => 'opel', 'dog' => ''),
array('name' => 'john', 'car' => '', 'dog' => 'albert')
);


I have been looking through PHP's documentation but can't find anything that will do this for me. Can anyone point me in the right direction? I don't even know an appropriate search term for what I want to achieve here, "array merge" isn't specific enough.

Answer

Here's what I would do:

  1. Merge your separate arrays into one (into a temporary var) using array_merge
  2. Get the unique keys of this new array using array_keys
  3. For each separate array, loop through the new keys array and add an empty value for each key that is not in the array. Then push the separate array into a final array.
Comments