Search code examples
phpcycle

Looking for some kind of "lookahead iteration" for grouping record sets


as it use to be, if you need to display list of something on site you have to use some looping construct to iterate over data.

In my case it's foreach() on <tr> of the table

foreach($candidates as $candidate)

and after that I am getting to values:

$candidate->id

Problem is one specific value, and it is enforcement. In my DB I have data like in table below, so for example for candidates_id = 600 there are enforcemement 1 and 0

id  |  candidates_id  | enforcement 
-------------------------------------
1   |       598       |      2
2   |       599       |      4
3   |       600       |      1
4   |       600       |      0

Until now everything is OKEY, I get values from DB and I echo it on site. Problem is that values like 0 or 1 have no meaning for end user. so I write IF / ELSE condition

if($candidate->enfor == 0)
 echo "TEXT1";
elseif($candidate->enfor == 1)
 echo "TEXT2";
else
 echo "some default text";

In the sample data there are two records with candidates_id=600 and different values for enforcement.
Right now the script produces two separate <tr> elements. One containing <td>TEXT1</td> and the other <td>TEXT2</td>.
I'm looking for a way to output <td>TEXT1,TEXT2</td> in the same html table row and column based on the fact that there are those two records for candidate_id=600 in the database.
I try to make another cycle for this but without any success. I am not even sure if I am thinking right way.

Can someone advise me how to make this work?

EDIT: my Query to DB is:

SELECT c.id, c.firstname, c.surname, c.email, c.process, c.search_work, c.note,c.registration_date,
       MAX(CASE WHEN cl.language = 'angličtina' THEN cl.level ELSE '-' END)AS 'en',
       MAX(CASE WHEN cl.language = 'němčina' THEN cl.level ELSE '-' END)AS 'ge',
       group_concat(DISTINCT ce.enforcement) as enfor,  
       group_concat(DISTINCT cc.city) as city  
FROM candidates AS c
LEFT JOIN candidates_languages AS cl ON c.id = cl.candidates_id
LEFT JOIN candidates_enforcement as ce on c.id = ce.candidates_id
LEFT JOIN candidates_city as cc on c.id = cc.candidates_id
GROUP BY c.id, c.firstname, c.surname, c.email DESC

Solution

  • The situation is the group_concat in your query that will return 0,1 for the id=600. You should do something like this:

    foreach($candidates as $candidate){
        // do your things ...
        $enfor_array = explode(',', $candidate->enfor);
        foreach($enfor_array as $enf) {
           if($enf == 0)
              echo "TEXT1";
           elseif($enf == 1)
              echo "TEXT2";
           else
              echo "some default text";
        }
    }