2015-12-22 140 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