0

I need to merge secuentially different arrays.

Let's say I have 3 and 2 arrays I need to merge all together. Currently I am using this:

$ppjson_data= json_encode(array_merge_recursive($ppposts[0][0],$ppposts[0][1],$ppposts[0][2],$ppposts[1][0],$ppposts[1][1]));

This works great.

Now the problem is that the number of arrays I may need to merge is not constant. There are $x and $y arrays to merge recursively, so how would you do it?

$x=5;
$y=10;
for ($i=0;$i<$x+1) {
  for ($j=0;$j<$y+1) {    
    $ppjson_data=json_encode(array_merge_recursive(...));
  }
}

Thank you for your help.

1 Answer 1

1

Call array_merge_recursive with the sub-arrays of your array as arguments using call_user_func_array:

$ppjson_data = json_encode(call_user_func_array('array_merge_recursive', $ppposts));

That creates an arra, in JSON it will be surrounded in []. If you want an object instead {} then cast it with (object):

$ppjson_data = json_encode((object)call_user_func_array('array_merge_recursive', $ppposts));
Sign up to request clarification or add additional context in comments.

4 Comments

Almost done, but the resulting json starts with "[" and finishes with "]". Any chances to avoid that?
I prefer the previous one and then: $ppjson_data=str_replace(array('[', ']'), '', $ppjson_data)
Depends on what you need, that might not be valid JSON. Check jsonlint.com
In my case, it is valid. Thank you!

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.