dongshanji3102 2014-08-04 15:59
浏览 34
已采纳

在PHP foreach中,在结果中分配一个带有行订单号的变量

I have a basic blogging system with many users / blogs and then each blog has many posts.

I want to be able to number each of the posts from each blog e.g. #1 #2 #3 #4.

I echo out the posts in a foreach like so:

SELECT * FROM posts WHERE blogID = :blogID ORDER BY dateposted DESC

foreach:

    $postcontent = $row['postcontent'];

    echo "<div>$postcontent</div>";

endforeach

That works fine, but what i want is to be able to say:

    echo "<div>$postNumber, $postcontent</div>";

I cant just do:

$postNumber = $row['ID'];

As all of the posts are in one table so the ids are not relevant in that sense.

How can i assign a variable with an increasing number (starting from 1) and give that to each foreach item.

Thanks!

  • 写回答

2条回答 默认 最新

  • duanbenzan4050 2014-08-04 16:06
    关注

    Increment the variable directly in your code:

    $postNumber = 1;
    foreach: 
        $postcontent = $row['postcontent'];
        echo "<div>$postNumber, $postcontent</div>";
        $postNumber++;
    endforeach
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?