0

Is it possible to merge non-specified number of array elements in PHP?

I received data through JSON string (n elements), then I used them to do n loops - each loop saves the result to a different array cell ($result[1], $result[2], $result[3], ... ,$result[n]). I would like to merge the results into a single array (I have to send single array through JSON). Everything works if I write manually array_merge ($result[1], $result[2], $result[3]), but I never know how many variables I will receive.

Thanks in advance

3
  • 2
    call_user_func_array('array_merge', $result); Commented Sep 8, 2014 at 21:22
  • Why do you save the result in different arrays if you can just throw them in the same array in the first place? Commented Sep 8, 2014 at 21:32
  • Hm this is a bit complicated ;) In main loop I execute 5 different SQL statements and save results into arrays: $result1, $result2, $result3, $result4, $result5. So after all n loops I got $result1[0], $result1[1], $result1[n], then $result2[0], $result2[1] etc... Commented Sep 8, 2014 at 21:52

1 Answer 1

1

Try this:

$yourListOfArrays = [$result[1], $result[2], ...];

call_user_func_array('array_merge',$yourListOfArrays);
Sign up to request clarification or add additional context in comments.

7 Comments

I wonder who down-voted this answer. Can you comment what's the issue?
I didn't downvote, but how is that different? You still need to know how many arrays.
No you dont. You can loop all your arrays into the $yourListOfArrays. Then you don't need to know them upfront. So for the OP it would probably just be $result. But it can not if the array contains other stuff.
If i could specifed $yourListOfArrays then i would be able to use simple array_merge($result[1], $result[2], ...) :) Rocket Hazmat's answer solved my problem.
My answer is exactly, 1:1, the same as his. I'm just showing the added array-buildup in case your $result object would contain more than just arrays. You might for example wanted to shift those non-array keys out of it. That's the reason. Besides that my answer is no different.
|

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.