问题
I have some PHP code here:
$a = 1;
echo "<div>$a</div>
<div class='alert alert-info' style='border-radius: 20px'>
<div style='padding: 10px; span5'>
<span class='label label-info' font-size='30px'><em>Tournament | Year | Round | Question # | Category</em></span><span style='margin-left: 500px; text-align: right'>ID: $id</span></div>
<b>$tournament |</b> <b>$year |</b> <b>$round |</b> <b>$num |</b> <b>$category</b>
<p><em>Question:</em> $question</p>
<div class='row'><div class='alert alert-info span7'><em><strong>ANSWER:</strong></em> $answer </div><div class='alert alert-info span2' align='right'>
<a href='#errorReportmodel' class='btn btn-inverse' data-toggle='modal'>Report an Error</a></div></div></div><hr>
";
I want a number ($a) to increment each time it is displayed (it is the results from a MySQL database search). Such as 1, 2, 3, 4, etc.
回答1:
You don't really have PHP code there. You have HTML which is being echoed out by PHP. I say this not to be pedantic, but to help you understand why this isn't the code you need to edit (or at least, not the whole of it).
It sounds like what you are looking for is a for loop. I'm guessing you already have one in somewhere above the code you pasted, but if not, you'll need to add it in. The type of code you are ultimately looking for is:
echo "<table><tr><th>Table Headers</th><th>Go Here</th></tr>";
$rowcount = 1;
foreach ($tablerows as $row) {
echo "<tr><td>".$rowcount."</td><td>Other row data></td><td>go here</td></tr>";
$rowcount++;
}
echo "</table>";
This will, for each row that you output, also output the current value of $rowcount
which, each time through the loop, gets incremented by one.
回答2:
Replace
<div>$a</div>
with
<div>".$a++."</div>
来源:https://stackoverflow.com/questions/17386454/php-incrementing