Jump to content

[SOLVED] turn field results sperated by comma into list


jesushax

Recommended Posts

hi all what im trying to do is

 

say $DogField = "german shepard,shitzu,husky, doberman, Lindsey Lohan";

 

how would i get that variable into

<ul>

<li>German Shepard</li>

<li>Shitzu</li>

<li>Husky</li>

</ul>

<ul>

<li>Doberman</li>

<li>Lindesy Lohan</li>

</ul>

 

so that every three <li>s a new list is created

 

my idea was something like str_replace(",","</li><li>",$Dogfield);

<?php
$dogArray = explode(",",$DogField);

$i=1;
foreach($dogArray as $dog) {
  if($i == 1) { echo "<ul>"; }
  echo "<li>" . $dog . "</li>";
  if($i == 3) {
     echo "</ul>";
     $i = 0;
   }
   $i++;
}
if($i ==2) { echo "</ul>"; }
?>

Here's another way:

 

<?php
$DogField = "german shepard,shitzu,husky, doberman, Lindsey Lohan";
$dogs = array_map('trim',explode(',',$DogField));
$st = 0;
$len = 3;
$part = array_slice($dogs,$st,$len);
while (!empty($part)) {
        echo '<ul><li>' . implode('</li><li>',$part) . "</li></ul>\n";
        $st += $len;
        $part = array_slice($dogs,$st,$len);
}
?>

 

Using the $len variable, you can easily change the number of elements in the generated lists.

 

Ken

who's method did you use ? I dont see how mine could have two <li> tags in a row

 

then again, neither of our methods would have all <li> tags without closing any of them, so maybe you just didn't copy/paste exactly what you saw

 

regardless, kenrbnsn's method is probably more dynamic

i used both, both of them display

 

<ul><li>Architects / Designers</li><li></li></ul>

 

the field is trades and contains this data

Architects / Designers,

 

there is not trailing spaces either

 

what you think it is?

Remove the trailing comma before exploding. The trailing comma is causing an empty entry in the array.

<?php
$str = "Architects / Designers,";
$ary = array_map('trim',explode(',',rtrim($str,',')));
?>

 

Ken

well heres the actual code, for what im using it for

 

EDIT: no sorry its displaying 1 blank <li>now

 

<?php
$TradesField = $row["Sect1_6"];
$trades = array_map('trim',explode(',',rtrim(',',$TradesField)));
$st = 0;
$len = 3;
$part = array_slice($trades,$st,$len);
while (!empty($part)) {
        echo '<ul><li>' . implode('</li><li>',$part) . "</li></ul>\n";
        $st += $len;
        $part = array_slice($trades,$st,$len);
}
?>

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.