PHP设置基于条件的变量

时间:2017-08-01 01:59:02

标签: php oracle

如果帖子标题与我的问题无关,我很抱歉。困惑如何给它。

示例我有以下数据表:

DEPARTMENT_ID_FK | EMAIL_ADDRESS
001              | a@example.com
002              | b@example.com
001              | c@example.com

当我查询它时,是否可以这样设置:
如果相同的DEPARTMENT_ID_FK然后将其显示为基于DEPARTMENT_ID_FK的变量组合值

while($dData = oci_fetch_array($q))
{
     $email = $dData['EMAIL_ADDRESS']; // I know when I echoing this variable, it will be like : a@example.comb@example.comc@example.com
}

我想要的是循环,我们可以知道:

DEPARTMENT_ID_FK | EMAIL_ADDRESS
001              | a@example.com, c@example.com
002              | b@example.com

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以让Oracle为您进行聚合

Oracle 11

SELECT DEPARTMENT_ID_FK, 
       LISTAGG(EMAIL_ADDRESS, ',') 
           WITHIN GROUP (ORDER BY EMAIL_ADDRESS) AS EMAIL_ADDRESS
  FROM table1
 GROUP BY DEPARTMENT_ID_FK

Oracle 10

SELECT DEPARTMENT_ID_FK, 
       RTRIM(XMLAGG(XMLELEMENT(e, EMAIL_ADDRESS, ',') 
           ORDER BY EMAIL_ADDRESS).EXTRACT('//text()').GETCLOBVAL(), ',') AS EMAIL_ADDRESS
  FROM table1
 GROUP BY DEPARTMENT_ID_FK

以下是两个查询的dbfiddle演示

结果:

DEPARTMENT_ID_FK | EMAIL_ADDRESS
-----------------+----------------------------
001              | a@example.com,c@example.com
002              | b@example.com
-----------------+----------------------------

或者只是在PHP中使用几个循环和条件

进行聚合
$agg = [];

while ($dData = oci_fetch_array($q)) {
    $dep = $dData['DEPARTMENT_ID_FK'];
    $email = $dData['EMAIL_ADDRESS'];

    if (isset($agg[$dep])) {
        $agg[$dep][] = $email;
        continue;
    }

    $agg[$dep] = [$email];
}

$result = [];

foreach ($agg as $dep => $emails) {
    $result[] = [
        'DEPARTMENT_ID_FK' => $dep,
        'EMAIL_ADDRESS' => implode(',', $emails),
    ];
}

print_r($result);

Demo

结果:

Array
(
    [0] => Array
        (
            [DEPARTMENT_ID_FK] => 001
            [EMAIL_ADDRESS] => a@example.com,c@example.com
        )

    [1] => Array
        (
            [DEPARTMENT_ID_FK] => 002
            [EMAIL_ADDRESS] => a@example.com
        )

)

答案 1 :(得分:0)

实现目标的简单方法。

$email = array(); while($dData = oci_fetch_array($q)) { $email[$dData['DEPARTMENT_ID_FK']] = (isset($email[$dData['DEPARTMENT_ID_FK']]) && $email[$dData['DEPARTMENT_ID_FK']] != '' ? ', ' : '').$dData['EMAIL_ADDRESS']; } foreach ($email as $key=>$val){ echo $key . ' => '. $val; }