多个foreach不嵌套
第一个代码块按预期工作。它是一个 foreach
,用于打印 $fnames
键值数组中的值。
foreach($fnames as $fname){
echo $fname;
}
$fnames 数组有一个与之对应的 $lnames
数组,我想同时打印 lname 和 fname,类似this:但它无法编译
foreach($fnames as $fname && $lnames as $lname){
echo $fname . " " . $lname;
}
我也尝试过这个,但也无法编译。
foreach($fnames,$lnames as $fname,$lname){
echo $fname . " " . $lname;
}
唯一编译的就是这个,但它没有给出正确的结果。
foreach($fnames as $fname){
foreach($lnames as $lnames){
echo $fname . " " . $lname;
}
}
如何在同一索引处的两个数组之间获得这种配对?
This first block of code works as expected. It's a foreach
to print values from an $fnames
key-value array.
foreach($fnames as $fname){
echo $fname;
}
The $fnames
array has an $lnames
array that correspond to it, and I'd like to print the lname with the fname at the same time, something like this: but it doesn't compile
foreach($fnames as $fname && $lnames as $lname){
echo $fname . " " . $lname;
}
I also tried this, but that too doesn't compile.
foreach($fnames,$lnames as $fname,$lname){
echo $fname . " " . $lname;
}
The only thing that compiled was this, but it didn't give correct results.
foreach($fnames as $fname){
foreach($lnames as $lnames){
echo $fname . " " . $lname;
}
}
How do I get this sort of pairing between the 2 arrays at the same index?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
另一种选择是:
Another option would be:
如果您不想组合数组,实际上需要同时运行两个生成器。幸运的是,PHP 有一种方法可以用数组来做到这一点。不过,这有点老派。
虽然这是一个稍微做作的示例,但它仍然是一种有用的技术。
If you don't want to combine the arrays, you actually need two generators running at once. Fortuantely, PHP has a way of doing this with arrays. It's a little bit old-school, though.
Whilst this is a slightly contrived example, it is still a useful technique to know.