Page 1 of 1

Implode failing, but why?

Posted: Tue Nov 17, 2009 7:23 pm
by jfulbrook
Hello there,

I am using an 'Implode' to separete my array with commas. Pretty standard I thought, but if fails every time, but why, I don't know? Any suggestions would be greatfully recieved, please see code below:

Code: Select all

 
$row_getJournalAuthors = mysql_fetch_array($query_getJournalAuthors);
$arr = array($row_getJournalAuthors['name']);
$str = implode(", ",$arr);
echo $str;
 
The result is just the names, but no commas or spaces; like this - John SmithJoe BloggsBurt Reynolds

Any clues anyone?

Thanks in advance!!

Re: Implode failing, but why?

Posted: Tue Nov 17, 2009 7:36 pm
by gth759k
you could try:

Code: Select all

 
$num = count($arr);
$lastnum = $num-1;
for ($i = 0; $i <= $num-2; $i++) {
    echo $arr[$i].', ';
}
echo $arr[$lastnum];
 

Re: Implode failing, but why?

Posted: Tue Nov 17, 2009 7:46 pm
by Weiry
Your problem is where you are setting your array.
I tested with the following and it worked fine.

Code: Select all

<?php
$arr = array("Joe Bloggs","Henry Jones","Fred Wallace");
$str = implode(", ",$arr);
echo $str;
?>
You need to loop through the array you have retrieved and then add each item into a new array if you were to use implode.

Code: Select all

 
$row_getJournalAuthors = mysql_fetch_array($query_getJournalAuthors);
foreach($row_getJournalAuthors as $author){
   $arr[] = $author;}
$str = implode(", ",$arr);
echo $str;

Re: Implode failing, but why?

Posted: Tue Nov 17, 2009 9:02 pm
by jfulbrook
Hello,

Thanks for the response so far.

The data for $row_getJournalAuthors['name'] is a first and second name in one field. i.e. John Smith.
The other field is an author ID.

When i use a for each loop like this:

Code: Select all

 
$row_getJournalAuthors = mysql_fetch_array($query_getJournalAuthors);
foreach($row_getJournalAuthors as $author){
   $arr[] = $author;}
$str = implode(", ",$arr);
echo $str;
 
I get:

144, 144, Paul smith, Paul smith, 1, 1144, 144, Paul smith, Paul smith, 1, 1, 147, 147, Lynne marks, Lynne marks, 1, 1

Please note there is a While loop going on behind the for each loop

Re: Implode failing, but why?

Posted: Tue Nov 17, 2009 10:02 pm
by Weiry
Well simply change the line:

Code: Select all

$arr[] = $author;
To what your field names are that you want...

Code: Select all

$arr[] = $author['name'];
The code i provided you was only an example, and in the example i was only using single string fields.
I can really only provide suggestions based on what you post.\, and the while loop was not in your original post.

Might i ask why you have a while loop around the updated code when the foreach loops through the array elements for you?