如何使SQLite3获取数组更干净?

时间:2014-03-30 15:02:09

标签: php sqlite

我正在使用SQLite3作为我的网络应用程序。一切正常。我能够访问数据库,创建和所有内容。

但是..当我使用以下代码检索信息时:

function db_select($username, $password, $database = 'Railway') {

$db = db_connect($database);

$result = $db->query("SELECT * FROM users ") or die('Query failed');
$rowss = array();

while ($row = $result->fetchArray()) {
    $rowss[] = $row;
}

print_r($rowss);
}

输出

Array ( 
[0] => Array ( [0] => John123 [username] => John123 
[1] => foo [password] => foo 
[2] => John [fname] => John 
[3] => Smith [lname] => Smith 
[4] => 21 [age] => 21 
[5] => john@gmail.com [email] => john@gmail.com 
[6] => Male [sex] => Male ) )

这个数组没有意义,如何单独检索fname,lname,age,username等信息?

有没有办法可以将其转换为以下形式?

Array (
username => John123,
password => foo,
fname => John
lname => Smith
)

2 个答案:

答案 0 :(得分:4)

尝试

$result->fetchArray(SQLITE3_ASSOC)

由于您似乎对列号不感兴趣。

答案 1 :(得分:1)

从PHP文档中找到了这个答案。

$row = array(); 

    $i = 0; 

     while($res = $result->fetchArray(SQLITE3_ASSOC)){ 

         if(!isset($res['username'])) continue; 

          $row[$i]['username'] = $res['username']; 
          $row[$i]['fname'] = $res['fname']; 
          $row[$i]['lname'] = $res['lname']; 
          $row[$i]['age'] = $res['age']; 
          $row[$i]['email'] = $res['email']; 
          $row[$i]['sex'] = $res['sex']; 
          $row[$i]['phone'] = $res['phone']; 
          $i++; 

      } 


print_r($row);

输出这个漂亮的阵列。

Array ( 
[0] => Array ( 
[username] => John123 
[fname] => John 
[lname] => Smith 
[age] => 21 
[email] => john@gmail.com 
[sex] => Male 
)