Home  >  Article  >  Backend Development  >  为什么这个arr不是个数组?

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

WBOY
WBOYOriginal
2016-06-06 20:16:551257browse

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

<code><?php $pdo=new PDO("mysql:host=localhost;dbname=t1","root","");
$stmt=$pdo->prepare("select * from user");
$stmt->execute();
$res=$stmt->fetchall(PDO::FETCH_ASSOC);
$arr=array();
foreach($res as $v){
    $arr=$v['username'];
    
}
?></code>

回复内容:

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

<code><?php $pdo=new PDO("mysql:host=localhost;dbname=t1","root","");
$stmt=$pdo->prepare("select * from user");
$stmt->execute();
$res=$stmt->fetchall(PDO::FETCH_ASSOC);
$arr=array();
foreach($res as $v){
    $arr=$v['username'];
    
}
?></code>

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

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

你的方法有问题

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

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

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

}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn