Yii(查询构建器)如何循环以获取所有列值

时间:2013-12-06 05:56:29

标签: php sql yii

我正在计算Department询问Concern的次数。

编辑:目前,当我cVardump时,查询会输出错误结果。但我在phpmyadmin中运行查询,它会输出正确的结果。

当我与循环一起实现时,它不起作用。它只输出一个Concern,其中数据库包含2 Concern

我不知道,但我认为这是在我的foreach循环中。任何帮助将不胜感激。

$query = $datacon->createCommand()

    ->select('COUNT(a.dept_id) as countDept,dept_name, concern')
    ->from('transaction a')
    ->join('department b' , 'a.dept_id = b.dept_id')
    ->group('dept_name', 'concern')
   // ->limit(10)
    ->queryAll();

    ob_end_clean();

/*CVarDumper::dump($query,15,true);
exit;*/



$html2 = '<h2 align="center"><small>FAQ (Sorted per Issue)</small></h2>

        <table border="1" cellspacing="0" cellpadding="4">

        <tr>
            <th align="center">Issue</th>
            <th align="center">Department</th>
            <th align="center">No. of times asked</th>
        </tr>';

        $count = 0;

     foreach ($query as $row)
        {
            $issue = $row['concern'];
            $dept_name = $row['dept_name'];
            $countDept = $row['countDept'];



    $html2 .= '
        <tr>
            <td>'.$issue.'</td>
            <td>'.$dept_name.'</td>
            <td align="center">'.$countDept.'</td>

        </tr>';
        }

    $html2 .= '</table> ';

    $pdf->writeHTML($html2, true, false, true, false, '');

编辑: VarDump的结果

array
(
    0 => array
    (
        'countDept' => '2'
        'dept_name' => 'Dialysis'
        'concern' => 'DSFSDFSDFSAFSAF'
    )
    1 => array
    (
        'countDept' => '4'
        'dept_name' => 'Nurse Ward'
        'concern' => 'DSFSDFSDFSAFSAF'
    )
)

2 个答案:

答案 0 :(得分:0)

我认为您只需按dept_name分组。

答案 1 :(得分:0)

试试这个,

foreach ($query as $row)
{
        foreach ($row as $r)
        {
            $issue = $r['concern'];
            $dept_name = $r['dept_name'];
            $countDept = $r['countDept'];
            $html2 .= '
            <tr><td>'.$issue.'</td>
            <td>'.$dept_name.'</td>
            <td align="center">'.$countDept.'</td></tr>';
        }
}

foreach ($query as $row)
{
        foreach ($row as $r)
        {
            $html2 .= '<tr><td>'.$r['concern'].'</td>
            <td>'.$r['dept_name'].'</td>
            <td align="center">'.$r['countDept'].'</td></tr>';
        }
}

 foreach ($query as $row)
    {
            for($i=0;$i<count($row);$i++)
            {
                $d=$row[$i];
                $html2 .= '<tr><td>'.$d['concern'].'</td>
                <td>'.$d['dept_name'].'</td>
                <td align="center">'.$d['countDept'].'</td></tr>';
            }
    }