我有两个数组,第一个是学生姓名,第二个是他最喜欢的作者选择,如下所示
$ student array如下
array (size=3)
0 => string 'Jane' (length=4)
1 => string 'Michelle' (length=8)
2 => string 'Mark' (length=4)
现在第二个数组作者$选择如下:
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)
现在我想展示学生的名字和他最喜欢的作者,即Jane最喜欢的作者是Mark Twaine,EA Poe,James Joyce和Michelle最喜欢的作者是Oscar,Leo Toby,James Joyce和Mark最喜欢的作者是Leo Toby,EA坡,詹姆斯乔伊斯......
到目前为止我已尝试过这个
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循环只使用递增键
限制为一个单个数组值答案 0 :(得分:3)
您可以使用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
答案 1 :(得分:2)
问题在于,您的第二个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/>";
}