我有一些奇怪的请求,所以我有两个数组
$students = array (
array(
"id" => 1,
"name" => "Sarah",
"grade" => "B"
),
array(
"id" => 2,
"name" => "David",
"grade" => "D"
)
);和
$lessons = array (
array(
"id" => 1,
"name" => "Maths",
"grade" => "005"
),
array(
"id" => 2,
"name" => "English",
"code" => "003"
),
array(
"id" => 3,
"name" => "Science",
"code" => "007"
),
array(
"id" => 4,
"name" => "Music",
"code" => "001"
)
);一般情况下,我用的是
foreach($students as $student)
{
echo '<h1>'.$student['name'].' - '.$student['grade'].'</h4>';
}循环遍历数组,这对某些事情是有好处的。
请注意,有时我只有一个学生在“学生”数组,有时在30左右,有时我有一课在“课程”阵列,有时50。
但在我的例子中,我只包括了2名学生和4节课。
所以,我想做的是,将这两个数组组合起来,创建一个类似于
莎拉
数学
英语
大卫
科学
音乐
如果我碰巧有5名学生和2节课,看起来就像
学生
学生
课程
学生
学生
课程
学生
如果我有2名学生和2节课,看起来就像
学生
课程
学生
课程
如果我有3名学生和1节课,看起来就像
学生
课程
学生
学生
如果我只有两个学生而没有上课,看起来就像
学生
学生
我很难解释这种分类叫什么
任何帮助都是令人惊奇的,我正在努力想出如何适应前轮循环。
发布于 2022-08-20 21:29:14
我认为这有两部分:
如果我们使用整数除法除以较大的数字除以较小的数字,我们就得到了我们的比率;我们只需要跟踪它周围的是:
$numStudents = count($students);
$numLessons = count($lessons);
if ( $numLessons >= $numStudents ) {
$studentSliceSize = 1;
$lessonSliceSize = intdiv($numLessons, $numStudents);
}
else {
$studentSliceSize = intdiv($numStudents, $numLessons);
$lessonSliceSize = 1;
}现在,我们可以将每个数组的取片、运算符和推他们放到组合列表的末尾:
$combinedArray = [];
$nextStudent = 0;
$nextLesson = 0;
while ( $nextStudent < $numStudents || $nextLesson < $numLessons ) {
$studentSlice = array_slice($students, $nextStudent, $studentSliceSize);
array_push($combinedArray, ...$studentSlice);
$nextStudent += $studentSliceSize;
$lessonSlice = array_slice($lessons, $nextLesson, $lessonSliceSize);
array_push($combinedArray, ...$lessonSlice);
$nextLesson += $lessonSliceSize;
}下面是现场演示将它们放在一起的函数。
https://stackoverflow.com/questions/73430018
复制相似问题