Chelle
Chelle

Reputation: 41

How to expand on implode() for separate strings dependent on value

In various places on my page I've used mysql_fetch_array() within a while loop to copy values into a new PHP array. From there I've used implode() to write the values into a string for display to the user. This has worked fine for me when I've only been dealing with one column or with two columns which can be combined onto one line for display.

Now I'm dealing with an array with two pieces of data, role and name. I want to display the output strings on different lines dependent on the value of role. It's a library database so I want all the names which relate the role of Author on one line, the names for the role of Publisher on another and so on.

$sql = mysql_query("select role, party_name from vw_roles where publication_id =  
$id order by role", $link);
while($role = mysql_fetch_array($sql)) {
    $roles[] = $role[role] . ": ". $role[party_name]; }
$the_roles = implode(" ; ", $roles);

Outputs: Author: Origen ; Bookseller: Gulielmus Morden ; Commentator for written text: Tarin, Jean ; Commentator for written text: Hoeschel, David ; Editor: Spencer, William ; Printer: Joan. Hayes

But then I'd need to try and split up the string into the various substrings, so that in my output table under the heading Author only Origen would be output. Is it better to go through the array $roles[] and separate the names into a new array for that role? So

if ($roles[role] == "Author") 
    $author[] = $roles[party_name]; 

with some form of iteration for each role? But then I'd need to specify every possible value for role in case it's been included for this specific record, which would make the code very long.

There's bound to be a better way to proceed here, I just haven't been able to find it yet. Anyone any ideas?

Upvotes: 1

Views: 490

Answers (1)

Daniel Boomgaardt
Daniel Boomgaardt

Reputation: 51

$sql = mysql_query("select role, party_name from vw_roles where publication_id =  
$id order by role", $link);
while($role = mysql_fetch_array($sql)) {
    $roles[$role[role]][] = $role[party_name]; }
foreach($roles as $role => $values) {
  echo "Role ".$role.": " implode(" ; ", $values);
}

Not sure if it is what you mean?

Upvotes: 2

Related Questions