简体   繁体   English

SQlite3 $ rows中不需要的键

[英]Unwanted keys in SQlite3 $rows

If a row in my SQlite3 table called 'data' looks like this: 如果我的SQlite3表中名为“数据”的行看起来像这样:

Gorilla|10|Black

And I'm getting it with this PHP: 而我用这个PHP:

$returned = array();

$result = $db->query("SELECT * FROM data");

foreach($result as $row) {
    $returned[] = $row;
}

echo json_encode($returned);

The resulting parsed JS Object in Array looks like this: 数组中生成的已解析的JS对象如下所示:

[{
  0: Gorilla,
  1: 10,
  2: Black,
  Age: 10,
  Animal: Gorilla,
  Color: Black
}]

Why are there 6 properties yet only 3 columns in the DB? 为什么数据库中只有6个属性却只有3列? I would like to be rid of the first 3 properties of the object and return only: 我想摆脱对象的前3个属性,仅返回:

[{
  Age: 10,
  Animal: Gorilla,
  Color: Black
}]

How? 怎么样? :) :)

This is the default behaviour of SQLiteDatabase::query . 这是SQLiteDatabase::query的默认行为。 As specified in the documentation : 文档中所指定:

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. 可选的result_type参数接受一个常数,并确定如何对返回的数组建立索引。 Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). 使用SQLITE_ASSOC将仅返回关联索引(命名字段),而SQLITE_NUM将仅返回数字索引( SQLITE_NUM字段编号)。 SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH将同时返回关联索引和数字索引。 SQLITE_BOTH is the default for this function. SQLITE_BOTH是此功能的默认值。

So write: 所以写:

$result = $db->query("SELECT * FROM data", SQLITE_ASSOC);

EDIT for PDO 编辑PDO

As you connect using PDO, the syntax becomes: 使用PDO连接时,语法变为:

$result = $db->query("SELECT * FROM data", PDO::FETCH_ASSOC);

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

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