Jump to content

[SOLVED] For Loop, Commas and SELECT Statement


hoopplaya4

Recommended Posts

Hello,

 

I currently have a SELECT statement (note, this is a simplified version):

 

SELECT group_concat(DISTINCT receiver.usrFirst, ' ', receiver.usrLast) as receiver_name,

COUNT(DISTINCT receiver.usrFirst) as receiver_count    //etc....

 

That outputs the following:

 

<?php
echo $row['receiver_name'];  //Which outputs: John Smith,John Doe,Jane Doe
echo $row['receiver_count']; //Which outputs: 3

 

I'd like to see if I can get some help writing the PHP to display it like:

 

John Smith, John Doe, and Jane Doe

 

1) Notice the <space> after the comma

2) Notice the <and> before the last person.

 

Any direction on this one would be very helpful.

untested.,  there may be a fancier way to do this, but i think this would work

<?php
$a = explode(",",$row['receiver_name']);
$count = $row['receiver_count'];
$i ==0;
foreach($a as $name) {
   if($i == 0) {
      echo $name;  //this is the first name
   }   
   if($i == $count) {
       echo " and " . $name ;  //this is the last name
   }
   else {
      echo ", " . $name;
   }
   $i++;
}

Use the following as the query

SELECT group_concat(DISTINCT receiver.usrFirst, ' ', receiver.usrLast SEPARATOR ', ' ) ) as receiver_name,
COUNT(DISTINCT receiver.usrFirst) as receiver_count    //etc....

 

This should generate a list like

John Smith, John Doe, Jane Doe

 

Now to add the and before the last name you'd use

 

$receiver_name = $row['receiver_name'];
$receiver_name = substr_replace($receiver_name, ' and', strrpos($receiver_name, ',')+1, 0);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.