Some days ago because the business needs to write a calculation of the combination of code, today sorted out for later use
<?php
/**
* Mathematical problems to solve: calculate the composition of C (a,1) * C (b, 1) * ... * C (n, 1), where C (n, 1) represents an arbitrary element from n elements
*
* Examples of practical problems to be addressed: There are M classes in a certain grade, the number of each class is different, and now a group is selected from each class.
* By the group to represent the grade to participate in a school event, please give all possible combinations
*/
/* ################################### Start calculation ################################### * *
/**
* Arrays that need to be arranged together
*
* Array Description: The array is a two-dimensional array, the first dimension index represents the class number, and the second dimension index represents the student number
*/
$CombinList = Array (1 => Array ("Student10", "Student11"),
2 => Array ("Student20", "Student21", "Student22"),
3 => Array ("Student30"),
4 => Array ("STUDENT40", "Student41", "Student42", "Student43"));
/* Compute the value of C (a,1) * C (b, 1) * ... * C (n, 1)
$CombineCount = 1;
foreach ($CombinList as $Key => $Value)
{
$CombineCount *= count ($Value);
}
$RepeatTime = $CombineCount;
foreach ($CombinList as $ClassNo => $StudentList)
{
The maximum number of repetitions of an element in a $StudentList that appears vertically after it is split into a combination
$RepeatTime = $RepeatTime/count ($StudentList);
$StartPosition = 1;
Start a cycle of students in each class
foreach ($StudentList as $Student)
{
$TempStartPosition = $StartPosition;
$SpaceCount = $CombineCount/count ($StudentList)/$RepeatTime;
for ($J = 1; $J <= $SpaceCount; $J + +)
{
for ($I = 0; $I < $RepeatTime; $I + +)
{
$Result [$TempStartPosition + $I] [$ClassNo] = $Student;
}
$TempStartPosition + + $RepeatTime * COUNT ($StudentList);
}
$StartPosition + + $RepeatTime;
}
}
/* Print Result * *
echo "<pre>";
Print_r ($Result);
?>