doudi5892 2016-09-22 12:27
浏览 81
已采纳

从循环/ while获取第一个条目

I need the first ID from a loop.

Loop:

while ($row = $db->sql_fetchrow($result))
{

echo ($row['post_id']) . '<br /><br />';

}

Echo Result:

817856<br /><br />817865<br /><br />817870<br /><br />817871<br /><br />817873<br /><br />817874<br /><br />

In this case I need only the Number 817856

var_dump

var_dump($row['post_id']);

var_dump Result:

string(6) "817856" string(6) "817865" string(6) "817870" string(6) "817871" string(6) "817873" string(6) "817874"

I tried:

reset and array_shift without success. Thank you

  • 写回答

2条回答 默认 最新

  • dt2015 2016-09-22 12:30
    关注

    You need to use a variable to track the loop and get the first ID while looping. By default you have to assign a variable as true and get the ID inside the loop also make that variable false so that the variable always stay false. Using the IF condition it will be OK.

    $flag = true;
    while ($row = $db->sql_fetchrow($result)){
        if($flag === true){
            $ID = $row['post_id'];
            $flag = false;
        }
        echo ($row['post_id']) . '<br /><br />';
    }
    
    echo $ID; // 817856
    

    If you need just the first ID then it will be shorter version. Cause the query only returns the first row when we don't use the loop.

    $row = $db->sql_fetchrow($result);
    echo $row['post_id']; //817856
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效