多个foreach不嵌套

发布于 2024-09-11 11:30:41 字数 687 浏览 4 评论 0原文

第一个代码块按预期工作。它是一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

眼泪淡了忧伤 2024-09-18 11:30:41
foreach($fnames as $key => $fname){ 
   echo $fname.' '.$lnames[$key]; 
}
foreach($fnames as $key => $fname){ 
   echo $fname.' '.$lnames[$key]; 
}
悸初 2024-09-18 11:30:41

另一种选择是:

foreach(array_map(null,$fnames,$lnames) as $name){
    echo $name[0].' '.$name[1];
}

Another option would be:

foreach(array_map(null,$fnames,$lnames) as $name){
    echo $name[0].' '.$name[1];
}
冷了相思 2024-09-18 11:30:41

如果您不想组合数组,实际上需要同时运行两个生成器。幸运的是,PHP 有一种方法可以用数组来做到这一点。不过,这有点老派。

reset($fnames);
reset($lnames);
do {
    print current($fnames).' '.current($lnames)."\n";
} while( next($fnames) && next($lnames) );

虽然这是一个稍微做作的示例,但它仍然是一种有用的技术。

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.

reset($fnames);
reset($lnames);
do {
    print current($fnames).' '.current($lnames)."\n";
} while( next($fnames) && next($lnames) );

Whilst this is a slightly contrived example, it is still a useful technique to know.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文