2015-12-22 102 views
0

如果我SQLITE3表中的一行称为“数据”是这样的:不需要钥匙

Gorilla|10|Black 

而且我这个PHP得到它:

$returned = array(); 

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

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

echo json_encode($returned); 

产生的在阵列解析的JS对象看起来是这样的:

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

为什么有6处房产,但只有3在DB列?我想摆脱对象的前3个属性,只返回:

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

如何? :)

+1

阅读本手册和使用'SQLITE_ASSOC' http://php.net/manual/en/function.sqlite-query.php – AbraCadaver

回答

1

这是SQLiteDatabase::query的默认行为。作为the documentation规定:

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

所以写:

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

编辑PDO

当您连接使用PDO,语法变为:

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

你说写的是d默认行为。 ^^您希望将'$ result = $ db-> query(“SELECT * FROM data”,SQLITE_ASSOC);' – Jon

+0

感谢您指出:) – trincot

+0

当我尝试使用SQLITE_ASSOC时收到以下错误: 使用未定义的常量SQLITE_ASSOC - 假定'SQLITE_ASSOC'@trincot请问为什么? – Donnie