简体   繁体   English

在PHP中循环的条件语句中向数组添加元素

[英]Add element to array in the conditional statement of a loop in PHP

I have this piece of code: 我有这段代码:

while ($i = $res->fetchArray(SQLITE3_ASSOC))
{
    $items[] = $i;
}

I tried neatening it to this: 我尝试将其整理为:

while ($items[] = $res->fetchArray(SQLITE3_ASSOC));

It looks very satisfying but I now get an extra element at the end of the array (when the call to fetchArray() returns false. Is there a way of writing this statement without getting the extra element at the end? 看起来很令人满意,但是我现在在数组的末尾得到了一个额外的元素(当对fetchArray()的调用返回false时,是否有一种编写此语句而不会在末尾得到额外的元素的方法?

If you're using PDO as your database library, you should use the fetchAll() method ( documentation ) 如果将PDO用作数据库库,则应使用fetchAll()方法( documentation

$items = $stmt->fetchAll(PDO::FETCH_ASSOC)

This will provide you a bidimensional associative array. 这将为您提供一个二维关联数组。 Its index goes from 0 to n-1 where n is the fetched rows count and every row contains an array with column names as indexes. 它的索引从0到n-1,其中n是获取的行数,每行包含一个以列名作为索引的数组。 For example: 例如:

$items[3]['id']

will contain the value stored in the id column of the 4th fetched row. 将包含存储在第4个提取行的id列中的值。

if you're using mysqli_* instead, there is mysqli_fetch_all() but it's discouraged because it's more expensive rather a loop of mysqli_fetch_array(), or so the documentation says. 如果您使用的是mysqli_ *,则建议使用mysqli_fetch_all (),但建议不要这样做,因为它比mysqli_fetch_array()的循环更昂贵,因此该文档说。

If you're using a third party library, consult the provided documentation. 如果您使用的是第三方库,请查阅提供的文档。 If there is none provided or there is no fetchAll equivalent it's a sign of poor quality. 如果未提供任何内容或没有等效的fetchAll则表明质量很差。 Drop it and use the native PDO instead. 删除它,改用本机PDO。

Since you're using SQLITE3 driver, i suggest you to look at this page: SQLITE (PDO) which explains how to use PDO with SQLITE3. 由于您使用的是SQLITE3驱动程序,因此我建议您查看以下页面: SQLITE(PDO) ,该页面说明了如何在SQLITE3中使用PDO。 Believe me, it's worth it. 相信我,这是值得的。 Most probably you won't stick to SQLITE for long and when you'll migrate to MySQL or PostgreSQL you'll thank me for this read. 很可能您不会长时间使用SQLITE,并且当您迁移到MySQL或PostgreSQL时,会感谢我的阅读。

PDO's main advantage is that's (usually) transparent to the user regarding which DB is below. PDO的主要优点是(通常)对于用户而言,下面的哪个DB是透明的。 Therefore, it shouldn't break your application if you change database, just change the PDO connection string and it'll be enough. 因此,如果您更改数据库,它不会破坏您的应用程序,只需更改PDO连接字符串就足够了。

尝试

while(($item=$res->fetchArray(SQLITE3_ASSOC))&&$items[]=$item);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM