I have some code that generates a random output based on prior parameters from different arrays
Data setup:
$persons = array("Old", "Young", "Child");
$moods = array("neutral", "happy", "sad");
$newarray= "";
shuffle($persons );
$persons2 = array_merge(...array_fill(1, 92, $persons ));
$persons2 = $array = array_slice($persons2, 1, 30);
shuffle($moods);
$moods2 = array_merge(...array_fill(1, 92, $moods));
$moods2 = $array = array_slice($moods2, 1, 30);
The desired output is an if-loop that generates strings of equally many old, young, and child objects that are each an equal amount of neutral, happy, and sad – something like
for ($x = 0; $x <= 30; $x++) {
$mood = $moods2[$x % (count($moods2))];
$person = $persons2 [$x % (count($persons2))];
$newarray .= "|".$person.",".$mood."|";
}
The problem with this code is that it does not ensure that the moods "happy", "sad", "neutral" are combined evenly with the person categories "Old", "Young", "Child".
The desired output is something like
$newarray= "|Old,happy||Old,sad||Old,netrual||Young,happy||Young,sad||Young,netrual||Child,happy||Child,sad||Child,neutral|";
such that there is 30 iterations and the possible persons/moods combinations occur equally frequently.
Not that I would also like that final output to be randomly ordered and that the code should work even when changing the number of iterations of the for-loop.
2
Answers
What you want to do is create to set of all possible permutations of your input, then fill an array of the desired size with the set of permutations then shuffle it.
You can do this in a more generic and reusable way (and support any number of input sets, not just two) using a class to create the Cartesian product.
Populate your cartesian product, then loop as many times as needed and grab the the next element in the shuffled array using circular index access (via modulus calculation).
Code: (Demo)