【问题标题】:Storing db value into php array and then looping through the array将 db 值存储到 php 数组中,然后遍历数组
【发布时间】:2016-02-20 11:34:46
【问题描述】:

将 db 值存储到数组中然后循环遍历数组与仅使用 while 循环有什么好处?

将 db 结果输出到数组:

$records = array();

if($results = $db->query("SELECT name, address FROM town")) {
    if($results->num_rows) {
        while($row = $results->fetch_object()) {
            $records[] = $row;
        }
        $results->free();
    }
}

遍历数组:

foreach($records as $r) {
    $r->name; 
}

VS 一个简单的 While 循环:

if($result = $db->query("SELECT name, address FROM town")) {
    if($count = $result->num_rows) {

        while($row = $result->fetch_object()) {
            echo $row->name, ' ', $row->address, '<br />';
        }

        $result->free();
    }
}

【问题讨论】:

    标签: php arrays mysqli


    【解决方案1】:

    最常见的用途是释放结果集,允许您在实际使用最初获得的结果之前执行其他数据库查询(更新、插入...)。

    【讨论】:

      【解决方案2】:

      只需一个 while 循环,打印结果既简单又快速,但在某些时候你想做更多的事情,然后只打印数组,然后如果你已经使用数组,它就会变得很方便。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-18
        • 2018-07-11
        • 1970-01-01
        • 2016-05-24
        • 2014-12-10
        • 1970-01-01
        相关资源
        最近更新 更多