1
votes

I have a database where I store publications: publication ID, Authors (priority is considered) and Publication title

I am having trouble with the second foreach as I need a loop to generate authors' names before moving to the title. the query will bring the result fine like:

PID Authors TITLE

1 NAME1 TITLE1

1 NAME2 TITLE1

1 NAME3 TITLE1

2 NAME1 TITLE2

2 NAME2 TITLE2

2 NAME3 TITLE2

and so on

I want the end result to be:

1 NAME1, NAME2, NAME3 TITLE1

2 NAME1, NAME2, NAME3 TITLE2

here is my code:

foreach ($query->result() as $row)
  {
    echo $row->PID;
    echo ": ";

    foreach ($query->result() as $row)
      {
        echo $row->AUTHORS;
        echo ", ";
      }

    echo $row->TITLE;
    echo "<br>" . "<br>";
  }
2
Why are you doing 2 foreach loops? And doesnt echo $row->PID</span>; break? Shouldnt it be echo $row->PID."</span>"; - Bolli
Because for each publication there are multiple authors. See the example I have provided. I need the second foreach to generate author names before I can type the title and the start with the next publication and so on so forth - Aadil

2 Answers

0
votes

You can use GROUP_CONCAT() function when retrieve data from your database instead of using two for loops.For example you can use

SELECT PID, GROUP_CONCAT(DISTINCT Authors SEPARATOR ','),TITLE1 FROM table GROUP BY PID;

0
votes

You used $query->result() on both query , try this

foreach ($query->result() as $row)
{
   echo $row->PID."</span>";
   echo ": ";

   echo implode(', ', $row->authors);

   echo $row->TITLE</span>;
   echo "<br>" . "<br>";
}