Supposing I have these 3 arrays
$array1 = array(1,2); $array2 = array(4,5); $array3 = array(7,8);
I need this output
1 4 7 1 4 8 1 5 7 1 5 8 2 4 7 2 4 8 2 5 7 2 5 8
One of my problems is that my array myght vary from 3 to 15 different arrays and each myght be empty (I might add a 0 just not to be empty) or have many values. If I have an empty array I also need to count that as a valid column. These values will be used to fill up a database in a specific order.
Is there any way I can do this?
How many combinations are there?
So first the question how many combinations are there? And the answer is you have to multiply the amount of every array with each other.
So (c = amount1):
And specific for your example:
*1 And if you wonder why I chose c for amount, because of the function count() in php
Getting all combinations together
How do we get now all combinations with the amount of arrays, which we have?
We loop through all our combinations, which we already have(Starting off with one combination, an "empty combination" (
$combinations = [];)), and for each combination we go through our next data array and combine each combination with each input data to a new combination.
Now we do this until we get the desired length for each combination.
So as an example:
* NAN: not a number
So as you can see in the above example we now have all combinations with the length of the amount of all arrays which we have.
But to get only the combinations with the desired length we are overwriting the result array each iteration, so that at the end only the combinations with the expected length are in the results array.
For associative arrays you only have to do a slight modification, which is:
First assign the arrays keys to a variable with
Use the keys in the second foreach loop to access the data array, means from: