简体   繁体   中英

PHP set Variable based on condition

I'm so sorry for the post title if it's not related with my question below. Confused how to give it.

Example I have this below data table:

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

When I query it, is it possible to set like this:
if same DEPARTMENT_ID_FK then show it as variable combine value based on 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
}

What I want is on looping we can know if:

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

Any help would be appreciated.

You can let Oracle do the aggregation for you

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

Here is a dbfiddle demo for both queries

Outcome:

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

Or just aggregate in php with a couple of loops and a conditional

$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

Result:

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
        )

)

实现目标的简单方法。

$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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM