如何在php中对foreach循环的项目进行编号


How to number items of foreach loop in php?

我正在使用它来创建一个mp3列表。

$mp3 = glob($directory . '*.mp3');
//print each file name
foreach($mp3 as $mp3)
{   
echo '
            <tr>
                <td class="one"><!--number goes here --></td>
                <td class="one">'. str_replace('(BDalbum.com).mp3','',basename($mp3)) .'</td>
                <td class="two">'. $_GET['s'] .'</td>
                <td class="three">'. $_GET['a'] .'</td>
                <td class="two">'. $_GET['a'] .'</td>
            </tr>
';
}

我想为列表中的每一项添加数字,比如,第一项:1,第二项:2等等。我该怎么做?

$listOfMp3 = glob($directory . '*.mp3');
foreach($listOfMp3 as $i => $mp3)
{
  echo $i; 
}

这不是最好的解决方案,但您可以使用计数器。这里有一个例子:

$mp3 = glob($directory . '*.mp3');
$c = 0;     //Set this value to 1 if you don't want to start with 0
foreach($mp3 as $mp3)
{   
echo '
        <tr>
            <td class="one">'.$c.'</td>
            <td class="one">'. str_replace('(BDalbum.com).mp3','',basename($mp3)) .'</td>
            <td class="two">'. $_GET['s'] .'</td>
            <td class="three">'. $_GET['a'] .'</td>
            <td class="two">'. $_GET['a'] .'</td>
        </tr>';
        $c++;
}

所以现在$c每次都会显示文件的编号。无论如何,您可以使用foreach键来执行完全相同的操作。