0

I have a site developed in php (codeigniter) and I want to merge some array with same structure. This is the constructor of my array:

$first = array();
$first['hotel'] = array();
$first['room'] = array();
$first['amenities'] = array();

/*
Insert data into $first array
*/

$second = array();
$second['hotel'] = array();
$second['room'] = array();
$second['amenities'] = array();

/*
Insert data into $second array
*/

After insert data I want to merge this array but the problem is that I have subarray inside it and I want to create a unique array like that:

$total = array();
$total['hotel'] = array();
$total['room'] = array();
$total['amenities'] = array();

This is the try to merge:

$total = array_merge((array)$first, (array)$second);

In this array I have only the $second array why?

4
  • I'm confused about the desired output your looking for Commented Jul 18, 2013 at 15:47
  • The desired output is an array like first r second but with two arrays merged @SamuelCook Commented Jul 18, 2013 at 15:47
  • Could you be looking for array_merge_recursive()? Commented Jul 18, 2013 at 15:51
  • Yes the solution is array_mege_recursive! @complex857 I thought that array_merge can do it! Commented Jul 18, 2013 at 15:53

3 Answers 3

1

Use the recursive version of array_merge called array_merge_recursive.

Sign up to request clarification or add additional context in comments.

1 Comment

I had to use array_replace_recursive instead.
0

It seems like array_merge doesn't do what you think it does: "If the input arrays have the same string keys, then the later value for that key will overwrite the previous one." Try this:

function merge_subarrays ($first, $second)
  $result = array();
  foreach (array_keys($first) as $key) {
    $result[$key] = array_merge($first[$key], $second[$key]);
  };
  return $result;
};

Then call it as:

$total = merge_subarrays($first, $second);

and, if I've correctly understood your question, $total will contain the result you're looking for.

Comments

0

There is no standard way of doing it, you just have to do something like:

<?php
$first = array();
$first['hotel'] = array('hello');
$first['room'] = array();
$first['amenities'] = array();

/*
Insert data into $first array
*/

$second = array();
$second['hotel'] = array('world');
$second['room'] = array();
$second['amenities'] = array();

$merged = array();
foreach( $first as $key => $value )
{
    $merged[$key] = array_merge( $value, $second[$key] );
}

print_r( $merged );

1 Comment

Why overwrite $first when you can't be sure it won't be needed later on?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.