Javi Javi - 1 year ago 127
PHP Question

Array merge recursive with an variable index

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?

for ($i=0;$i<$x+1) {
for ($j=0;$j<$y+1) {

Thank you for your help.

Answer Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download