开发者

Is it possible to use foreach to auto-increment from the value of an array?

I have an array that sets a number for each animal. I want to create a loop which will auto-increment for however number of animals there are

$animal = array(
    'dog开发者_Python百科' => 2,
    'cat' => 4,

    );
foreach($animal as $pet => $num) {
    echo(sprintf('this is %s number $s', $pet, $num));
    };

Ideally I want it to display

this is dog number 1

this is dog number 2

this is cat number 1

this is cat number 2

this is cat number 3

this is cat number 4


I dont think there is any need of another nested for loop , try this

    $animal = array(
      'dog' => 2,
      'cat' => 4,
    );

    $i = 1;
    foreach($animal as $pet => $num) {
      echo "this is $pet number $i";
      $i++;
    };


$animal = array(
'dog' => 2,
'cat' => 4,

);

foreach($animal as $pet => $num){
$i = 0;
while($num > 0)
{
    $i++;
    echo "This is $pet number $i<br/>";
    $num--;
}
}


Is this what you mean? Probably not the most elegant solution but it works

$animal = array(
    'dog' => 2,
    'cat' => 4,

    );


foreach ($animal as $pet => $num):

    for ($i=1; $i <= $num; $i++):

        echo 'This is '.$pet.' number '.$i;

    endfor;

endforeach;


You can try this.

$animal = array(
    'dog' => 2,
    'cat' => 4,

    );
foreach($animal as $pet => $num) {
for($i=1;$i<=$num;$i++){
echo "this is $pet number $i";
}
};


It looks like you want something more like:

foreach($animal as $pet => $count){
    for($i = 1; $i <= $count; $i++){
        printf('this is %s number %d', $pet, $i);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜