Home > Backend Development > PHP Tutorial > 怎样得到这样一个形式的数组呢?

怎样得到这样一个形式的数组呢?

WBOY
Release: 2016-06-06 20:16:49
Original
1071 people have browsed it

我想要这样的一个结果Array ( [0] => wang [1] => zhang )
现在的结果是这样的 得到是两个数组 Array ( [0] => wang ) Array ( [0] => wang [1] => zhang )
把数组声明写在循环里面也不行 那么怎么改呢?

<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){
  array_push($arr, $v['username']);
  print_r($arr);
}
?></code>
Copy after login
Copy after login

回复内容:

我想要这样的一个结果Array ( [0] => wang [1] => zhang )
现在的结果是这样的 得到是两个数组 Array ( [0] => wang ) Array ( [0] => wang [1] => zhang )
把数组声明写在循环里面也不行 那么怎么改呢?

<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){
  array_push($arr, $v['username']);
  print_r($arr);
}
?></code>
Copy after login
Copy after login

完全没看懂……
我教你怎么改,把 print_r($arr); 移到循环外面你就得到你想要的了……认真弄懂程序每一行的意思吧。

:75… #+ ?他‘链接

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template