数组未填充记录

时间:2013-08-01 11:59:32

标签: php arrays variables select while-loop

使用第一组代码我可以打印数组,但是第二段是为了将数组存储到一个变量中,但这不起作用吗?数组是空的吗?

 $stmt = $conn->prepare("SELECT admin_name FROM adminuser_tbl");
    if ($stmt->execute()) {
       while ($row = $stmt->fetch()) {
    print_r($row);
    }
  }

不在

下面工作
 $stmt = $conn->prepare("SELECT admin_name, adminuser_id FROM adminuser_tbl");
      if ($stmt->execute()) {
          $user_list = array();
     while ($row = $stmt->fetch()) { 
          $user_list[$row->adminuser_id] = $row->admin_name; 
     }
   }

如果我从第一段打印数组结果,它们都被设置为[0] ???

Array ( [admin_name] => User1 [0] => User1 ) Array ( [admin_name] => User2 [0] => User2 ) Array ( [admin_name] => User3 [0] => User3 ) Array ( [admin_name] => User4 [0] => User4 ) 

1 个答案:

答案 0 :(得分:2)

如果要将行作为对象获取,则需要设置获取模式。默认值为PDO::FETCH_BOTH,它为您提供包含整数和命名键的数组。 (参见你的print_r输出)

$stmt = $conn->prepare("SELECT admin_name, adminuser_id FROM adminuser_tbl");
if ($stmt->execute()) {
    $stmt->setFetchMode(PDO::FETCH_OBJ);
    $user_list = array();
    while ($row = $stmt->fetch()) {
        $user_list[$row->adminuser_id] = $row->admin_name;
    }
}

或者只使用foreach循环,因为PDOStatement实现了Traversable接口。

$stmt = $conn->prepare("SELECT admin_name, adminuser_id FROM adminuser_tbl");
if ($stmt->execute()) {
    $stmt->setFetchMode(PDO::FETCH_OBJ);
    $user_list = array();
    foreach ($stmt as $row) {
        $user_list[$row->adminuser_id] = $row->admin_name;
    }
}

对于其他获取模式,请在此处查看:pdo.constants