Jump to content

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);

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.