在 PHP 中,是否可以使用多个“索引”变量进行 foreach
循环,类似于以下示例(它不使用正确的语法)?
foreach ($courses as $course, $sections as $section)
如果不行,有没有好的方法可以达到相同的效果?
在 PHP 中,是否可以使用多个“索引”变量进行 foreach
循环,类似于以下示例(它不使用正确的语法)?
foreach ($courses as $course, $sections as $section)
如果不行,有没有好的方法可以达到相同的效果?
为了达到这样的结果,你可以这样做
foreach (array_combine($courses, $sections) as $course => $section)
但这只适用于两个数组
$courses
是数字字符串,它们将被转换为整数。 - hakre如果两个数组大小相同,您可以使用for
循环:
for($i=0, $count = count($courses);$i<$count;$i++) {
$course = $courses[$i];
$section = $sections[$i];
}
TRY -
1)
<?php
$FirstArray = array('a', 'b', 'c', 'd');
$SecondArray = array('1', '2', '3', '4');
foreach($FirstArray as $index => $value) {
echo $FirstArray[$index].$SecondArray[$index];
echo "<br/>";
}
?>
<?php
$FirstArray = array('a', 'b', 'c', 'd');
$SecondArray = array('1', '2', '3', '4');
for ($index = 0 ; $index < count($FirstArray); $index ++) {
echo $FirstArray[$index] . $SecondArray[$index];
echo "<br/>";
}
?>
您需要像这样使用嵌套循环:
foreach($courses as $course)
{
foreach($sections as $section)
{
}
}
foreach($courses as $key => $course)
{
$section = $sections[$key];
}
$courses as $key => $course
答案。区别在于,接受的答案仅限于两个自定义字段,而这个答案允许任意数量的字段,因此更加灵活。 - edwinbradfordfor ($i = 0; $i < count($courses) && $i < count($sections); ++$i) {
$course = $courses[$i];
$section = $sections[$i];
//here the code you wanted before
}
reset($sections);
foreach ($courses as $course)
{
list($section) = each($sections);
}
具体来说,这会产生什么影响?$courses
和$sections
只是两个分开的数组,你希望对它们的值执行相同的函数吗?你可以尝试以下代码:
foreach(array_merge($courses, $sections) as $thing) { ... }
当然,这里做出了有关array_merge
的所有通常假设。
还是说$sections
来自于$course
,你想对每个课程中的每个章节都做些什么?
foreach($courses as $course) {
foreach($sections as $section) {
// Here ya go
}
}
像这样吗?
foreach($array as $b=>$c){
}