I have the following code:
if(hasRows($resultC)){
while($row = mysql_fetch_row($resultC)) {
$mescategories = '<span><a href="' . CalRoot .
'/index.php?com=searchr开发者_Go百科esult&t=' . $row[0] .
'" rel="tag" class="eventMain">' . cOut($row[1]) . '</a></span> | ' ;
echo $mescategories;
}//end while
}//end if
The rendered output looks like:
cat 1 | cat 2 | cat 3 | cat 4 |
How do I prevent the last |
character being rendered.
$catArray = array();
if(hasRows($resultC)){
while($row = mysql_fetch_row($resultC)){
array_push($catArray, '<span><a href="' . CalRoot . '/index.php?com=searchresult&t=' . $row[0] . '" rel="tag" class="eventMain">' . cOut($row[1]) . '</a></span>');
}//end while
echo implode('|', $catArray);
}//end if
You could count the number of rows using mysql_num_rows($resultC)
, and have a counter on your loop. Alternatively, the way I'd do it is something like:
if(hasRows($resultC)){
// Create an empty array
$links = array( );
while($row = mysql_fetch_row($resultC)){
// Add each text link to the array
$links[] = '<span><a href="' . CalRoot . '/index.php?com=searchresult&t=' . $row[0] . '" rel="tag" class="eventMain">' . cOut($row[1]) . '</a></span>' ;
}
// "Glue" the array back together using implode, with the separator between each.
echo implode(' | ', $links );
}
How about putting in a conditional statement. Count the size of the row and if $count=$maxcount then don't echo the "|" character.
$i = 0; //set before while loop
$i++; //inserted into while loop
if ($i != mysql_num_rows($resultC) ) { //inserted into while loop
$mescategories .= " | " ;
}
mysql_num_rows will tell how many rows there are in the query, and then will append the pipe character for each row except the last one.
EDIT: I think the $i++ should come before the if statement, actually.
I have not checked your formatting. Just added a "first" variable.
if(hasRows($resultC)){
$first = true;
while($row = mysql_fetch_row($resultC)){
$mescategories = ' '.($first ? "":"|").' <span><a href="' . CalRoot . '/index.php?com=searchresult&t=' . $row[0] . '" rel="tag" class="eventMain">' . cOut($row[1]) . '</a></span> ' ;
echo $mescategories;
$first = false;
}//end while
}//end if
try
if(hasRows($resultC)){
$i=0;
while($row = mysql_fetch_row($resultC)){
$spaceline =($i>0) ? '|' : '';
$mescategories = '<span><a href="' . CalRoot . '/index.php?com=searchresult&t=' . $row[0] . '" rel="tag" class="eventMain">' . cOut($row[1]) . '</a></span>' ;
$i++;
echo $spaceline.$mescategories;
}//end while
}//end if
Just do
echo substr($mescategories, 0, -1);
instead of echo $mescategories
you let it put | after every instance and then delete the last char
else if you need to know the last key of an array you use:
end($array);
$lastKey = key($array);
but don't forget to reset before you do things with it
reset($array);
精彩评论