我试图从fetchAll中获取一个结果,并将一些数据放入一个数组中。
相关PHP:
$catcodessql = "select distinct cat_code from mytable";
$result2 = $dbh->query($catcodessql)->fetchAll(PDO::FETCH_ASSOC); 这将返回如下内容:
array(4) {
[0]=>
array(1) {
["cat_code"]=>
string(3) "edu"
}
[1]=>
array(1) {
["cat_code"]=>
string(3) "inc"
}
[2]=>
array(1) {
["cat_code"]=>
string(3) "net"
}
[3]=>
array(1) {
["cat_code"]=>
string(3) "occ"
}我想要的是所有这些字符串,以便稍后在PHP中动态地将这一行放在一起:
$allcategories = array ('edu', 'inc', 'net', 'occ' );因此,我需要创建一个变量来替换这个部分:'edu', 'inc', 'net', 'occ'
我尝试过几个while函数,但显然它们不正确。
发布于 2015-01-27 19:12:15
如果只想检索唯一类别,则可以直接使用查询进行检索:
$stmt = $dbh->prepare("select GROUP_CONCAT( cat_code SEPARATOR ',') as cat_code from ( select distinct cat_code from mytable) as m");
$stmt->execute();
$row = $stmt->fetch();
$categories = explode(",",$row["cat_code"]);
var_dump($categories);发布于 2015-01-27 18:43:09
PHP >= 5.5.0用于array_column()或使用栏()
$allcategories = array_column($result2, 'cat_code');或者foreach在query上
foreach($dbh->query($catcodessql) as $row) {
$allcategories = $row['cat_code'];
}https://stackoverflow.com/questions/28177682
复制相似问题