Heim  >  Artikel  >  Backend-Entwicklung  >  为什么这个arr不是个数组?

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

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

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

<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>

}

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn