开发者

Why is my variable not iterating in this foreach loop?

I am trying to make a div ID have a unique name by using a variable to iterate through the number of times it gets looped. For some reason my $k variable doesn't seem to be advancing. Here is the code:

<?php foreach($files as $media)
                { 
                    $k = 0;
                    ?>
                    <h3><?php echo $output[$j] ?></h3>
                    <div id='mediaspace<?php echo $k ?>'>This text will be replaced</div>

                    <script type='text/javascript'>
                      ...
                      so.write('mediaspace<?php echo $k ?>');
                    </script>
                <?php 
                $k = $k+1;
        开发者_如何学C        } ?>

My HTML output just gives me a 0 for $k every time the loop is run:

<div id='mediaspace0'>This text will be replaced</div>


                    <script type='text/javascript'>
                     ...                  so.write('mediaspace0');
                    </script>
                                        <h3>Rattletree Marimba Day</h3>
                    <div id='mediaspace0'>This text will be replaced</div>

                    <script type='text/javascript'>
                      ...                 so.write('mediaspace0');
                    </script>

Any help greatly appreciated!


Of course:

$k = 0;

Reset the variable before the loop.


$k = 0;

at the start of the loop resets your $k to 0 at the start of each iteration.

Move it outside the loop:

<?php 
$k = 0;
foreach($files as $media)
{ 
...


You are setting $k to 0 at the begining of your foreach.

Set it outside.

$k = 0;
foreach($files as $media) {
...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜