execute();$res=$stmt->fetchall(PDO::FETCH_ASSOC);$">
当前位置:Gxlcms > PHP教程 > 为什么这个arr不是个数组?

为什么这个arr不是个数组?

时间:2021-07-01 10:21:17 帮助过:29人阅读

我就是想把查询结果放到一个数组里面 改怎么写呢 我的哪里不对呢?

  1. <code><!--?php
  2. $pdo=new PDO("mysql:host=localhost;dbname=t1","root","");
  3. $stmt=$pdo--->prepare("select * from user");
  4. $stmt->execute();
  5. $res=$stmt->fetchall(PDO::FETCH_ASSOC);
  6. $arr=array();
  7. foreach($res as $v){
  8. $arr=$v['username'];
  9. }
  10. ?></code>

回复内容:

我就是想把查询结果放到一个数组里面 改怎么写呢 我的哪里不对呢?

  1. <code><!--?php
  2. $pdo=new PDO("mysql:host=localhost;dbname=t1","root","");
  3. $stmt=$pdo--->prepare("select * from user");
  4. $stmt->execute();
  5. $res=$stmt->fetchall(PDO::FETCH_ASSOC);
  6. $arr=array();
  7. foreach($res as $v){
  8. $arr=$v['username'];
  9. }
  10. ?></code>

$arr=$v['username'];这样$arr一直在被覆盖!你是想表达这个意思吧: $arr[]=$v['username']

你这样写的 话 所有的 结果一直只有一个 就是 $arr[0],

你的方法有问题

  1. <code class="PHP">foreach($res as $v){
  2. $arr=$v['username'];
  3. }</code>

建议修改成
foreach($res as $v){

  1. <code>$arr[]=$v['username'];</code>

}

人气教程排行