我有两个数组,一个是学生名,另一个是他最喜欢的作者,如下所示
$student数组如下所示
array (size=3)
0 => string 'Jane' (length=4)
1 => string 'Michelle' (length=8)
2 => string 'Mark' (length=4)
现在,第二个数组作者$selection如下所示:
array (size=3)
0 =>
array (size=3)
0 => string 'Mark Twaine' (length=11)
1 => string 'E A Poe' (length=7)
2 => string 'James Joyce' (length=11)
1 =>
array (size=3)
0 => string 'Oscar' (length=11)
1 => string 'Leo Toby' (length=7)
2 => string 'James Joyce' (length=11)
2 =>
array (size=3)
0 => string 'Leo Toby' (length=11)
1 => string 'E A Poe' (length=7)
2 => string 'James Joyce' (length=11)
现在我想展示学生的名字和他最喜欢的作家。简最喜欢的作家是马克·吐温,E·A·坡,詹姆斯·乔伊斯和米歇尔最喜欢的作家是奥斯卡,利奥·托比,詹姆斯·乔伊斯和马克最喜欢的作家是利奥·托比,E·A·坡,詹姆斯·乔伊斯……
到目前为止我已经试过了
foreach( $student as $key => $val ) {
echo $val." read ";
foreach( $selection as $key1 ) {
foreach ($key1 as $key2 => $val2){
echo $val2;
echo ' and ';
}
echo "<br/>";
}
并将此作为输出
Jane favorite is Mark Twaine and E A Poe and James Joyce and
Oscar and Leo Toby and James Joyce and
Leo Toby and E A Poe and James Joyce and
Michelle favorite is Mark Twaine and E A Poe and James Joyce and
Oscar and Leo Toby and James Joyce and
Leo Toby and E A Poe and James Joyce and
Mark favorite is Mark Twaine and E A Poe and James Joyce and
Oscar and Leo Toby and James Joyce and
Leo Toby and E A Poe and James Joyce and
而不是
Jane favorite is Mark Twaine and E A Poe and James Joyce
Michelle favorite is Oscar and Leo Toby and James Joyce
Mark favorite is Leo Toby and E A Poe and James Joyce
我希望foreach循环仅限制为一个具有递增键的数组值。
发布于 2018-03-30 06:23:15
您可以使用array_combine()
结合学生和选择。然后,使用implode()
回显每个学生的选择:
$student = ['Jane','Michelle','Mark'];
$selection = [
['Mark Twaine', 'E A Poe', 'James Joyce'],
['Oscar', 'Leo Toby', 'James Joyce'],
['Leo Toby', 'E A Poe', 'James Joyce'],
];
$comb = array_combine($student, $selection);
foreach ($comb as $student => $item) {
echo $student . ' favorite is '. implode(' and ', $item). '<br>' ;
}
产出:
Jane favorite is Mark Twaine and E A Poe and James Joyce
Michelle favorite is Oscar and Leo Toby and James Joyce
Mark favorite is Leo Toby and E A Poe and James Joyce
发布于 2018-03-30 06:28:04
问题是,您的第二个foreach()
(foreach( $selection as $key1 ) {
)正在遍历每个学生的所有选择。此时,您只需为相应的学生选择所选内容(将$student数组的键与$selection数组的键匹配)。
$student = ['Jane', 'Michelle', 'Mark'];
$selection = [['Mark Twaine','E A Poe','James Joyce'],
['Oscar','Leo Toby','James Joyce'],
['Leo Toby','E A Poe','James Joyce']];
foreach( $student as $key => $val ) {
echo $val." read ";
foreach( $selection[$key] as $val2 ) {
echo $val2;
echo ' and ';
}
echo "<br/>";
}
您可以看到内部foreach
使用来自第一个数组的$key
来选择要循环的选择。
您可以使用implode()
缩短内部循环,这还可以消除输出中的额外“和”。
foreach( $student as $key => $val ) {
echo $val." read ".implode(' and ', $selection[$key])."<br/>";
}
https://stackoverflow.com/questions/49569368
复制相似问题