PHP PDO组按列名称查询结果 - php

以下PDO查询返回以下结果:

$db = new PDO('....');
$sth = $db->prepare('SELECT ...'); 

结果如下:

 name   curso   
ABC stack
CDE stack
FGH stack
IJK stack
LMN overflow
OPQ overflow
RST overflow

我需要像这样构建HTML:

<p>stack</p>
ABC<br/>
CDE<br/>
...<br/>
<p>overflow</p>
LMN<br/>
OPQ<br/>

这是我正在尝试的:

$sth->execute();
  //$curso = $sth->fetch();
  $id = $sth->fetchColumn(1);
  echo "<p>".mb_convert_encoding($id,'utf-8', 'iso-8859-1').'</p>'; 
  while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    echo (mb_convert_encoding($row['name'],'utf-8', 'iso-8859-1')).'<br/>';
  }

但这将删除每个组的名字,例如:

 <p>stack</p>
    CDE<br/>
    ...<br/>

参考方案

也许您可以尝试使用以下代码来打印结果:

$sth->execute();
$curso = '';
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    if ($row['curso'] !== $curso) {
        $curso = $row['curso'];
        echo '<p>' . mb_convert_encoding($curso, 'utf-8', 'iso-8859-1') . '</p>';
    }
    echo mb_convert_encoding($row['name'], 'utf-8', 'iso-8859-1') . '<br />';
}

php Singleton类实例将在多个会话中保留吗? - php

举一个简单的例子,如果我想计算一个不使用磁盘存储的脚本的命中次数,我可以使用静态类成员来执行此操作吗?用户1:<?php $test = Example::singleton(); $test->visits++; ?> 用户2:<?php $test = Example::singleton(); $test->visits+…

PHP:对数组排序 - php

请如何排序以下数组Array ( 'ben' => 1.0, 'ken' => 2.0, 'sam' => 1.5 ) 至Array ( 'ken' => 2.0, 'sam' => 1.5, 'ben' =&…

PHP strtotime困境 - php

有人可以解释为什么这在我的服务器上输出为true吗?date_default_timezone_set('Europe/Bucharest'); var_dump( strtotime('29.03.2015 03:00', time()) === strtotime('29.03.2015 04:00�…

PHP-全局变量的性能和内存问题 - php

假设情况:我在php中运行一个复杂的站点,并且我使用了很多全局变量。我可以将变量存储在现有的全局范围内,例如$_REQUEST['userInfo'],$_REQUEST['foo']和$_REQUEST['bar']等,然后将许多不同的内容放入请求范围内(这将是适当的用法,因为这些数据指的是要求自…

php-casperjs获取内部文本 - php

我正在为casperjs使用php包装器-https://github.com/alwex/php-casperjs我正在网上自动化一些重复的工作,我需要访问一个项目的innerText,但是我尚不清楚如何从casperjs浏览器访问dom。我认为在js中我会var arr = document.querySelector('label.input…