php foreach just looping on one value of array

2020-08-01 05:42发布

问题:

Here is my code:

$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;
}
}

and here's the output:

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

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?

回答1:

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;
    }
}

Output:

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

Demo on 3v4l.org



标签: php foreach