PHP的foreach只是循环数组的一个值 [英] php foreach just looping on one value of array

查看:152
本文介绍了PHP的foreach只是循环数组的一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

$bag3 = 7;
$row = 4;
$nom = 1;
$arr = array("red", "green", "blue", "yellow");
while ($bag3){
while ($nom <= $bag3){
    echo $ay." ".$row;
    $nom++;
    $row++;
}if ($nom == $bag3){
    $nom = 1;
}
}

这是输出:

red 4red 5red 6red 7red 8red 9red 10 

我希望它遍历所有数组值:redgreenblueyellow. 像这样:

I want it to loop through all the array values: red, green, blue, and yellow. like this:

red 4red 5red 6red 7red 8red 9red 10green 11green 12green 13green 14green 15green 16green 17blue 18blue 19blue 20blue 21blue 22blue 23blue 24yellow 25yellow 26yellow 27yellow 28yellow 29yellow 30yellow 31

我应该更改我的代码吗?

What should I change in my code?

推荐答案

您可以使用数组上的foreach循环和$nom从1到$bag3for循环来简化代码:

You can simplify your code with a foreach loop over the array and a for loop for $nom from 1 to $bag3:

$bag3 = 7;
$row = 4;
$arr = array("red", "green", "blue", "yellow");
foreach ($arr as $ay) {
    for ($nom = 1; $nom <= $bag3; $nom++, $row++){
        echo $ay." ".$row;
    }
}

输出:

red 4red 5red 6red 7red 8red 9red 10green 11green 12green 13green 14green 15green 16green 17blue 18blue 19blue 20blue 21blue 22blue 23blue 24yellow 25yellow 26yellow 27yellow 28yellow 29yellow 30yellow 31

在3v4l.org上进行演示

这篇关于PHP的foreach只是循环数组的一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆