5

I have a set of numbers in a table field in database, the numbers are separated by comma ','. I am trying to do the following:

Step 1. : SELECT set of numbers from database and explode it to array :

$array =  explode(',', $set_of_numbers);

Step 2. : Print each element of the array as list item by using foreach loop :

foreach ($array as $list_item => $set_of_numbers){
    echo "<li>";
    print_r(array_list_items($set_of_numbers));
    echo "</li>";}

Please anybody tell me what is wrong. Thank you.

4

6 回答 6

25
$numbers = '1,2,3';

$array =  explode(',', $numbers);

foreach ($array as $item) {
    echo "<li>$item</li>";
}
于 2013-04-27T21:35:50.150 回答
2

Assuming your original $set_of_numbers is simply a CSV string, something like 1,2,3,4,..., then your foreach is "mostly" ok. But your variable naming is quite bonkers, and your print-r() call uncesary:

$array = explode(',', $set_of_numbers);
foreach($array as $key => $value) {
   echo "<li>$key: $value</li>";
}

Assuming that 1,2,3,4... string, you'd get

<li>0: 1</li>
<li>1: 2</li>
<li>2: 3</li>
etc...
于 2013-04-27T21:37:04.763 回答
1
$numbers = "1,2,3";

$array =  explode(",", $numbers);

/* count length of array */
$arrlength = count($array);

/* using for while */
$x = 0; 

while ($x < $arrlength) {

  echo "<li>$array[$x]</li>" . PHP_EOL;
  $x++;

}
echo PHP_EOL;

/* using for classic */
for ($x = 0; $x < $arrlength; $x++) {

  echo "<li>$array[$x]</li>" .  PHP_EOL;

}
echo PHP_EOL;    

/* using for each assoc */
foreach ($array as $value) {

  echo "<li>$value</li>" .  PHP_EOL;

}
echo PHP_EOL;    

/* using for each assoc key */
foreach ($array as $key => $value) {

  echo "<li>$key => $value</li>" .  PHP_EOL;

}

body, html, iframe { 
  width: 100% ;
  height: 100% ;
  overflow: hidden ;
}
<iframe src="https://ideone.com/ZqT4Yi" ></iframe>

于 2017-07-25T16:25:11.130 回答
1

You actually don't need to explode on the commas. You can just replace each comma with an ending tag followed by an opening tag and then wrap your whole string in an opening and closing tag.

$set_of_numbers = '1,2,3';
echo '<li>' . str_replace(',', '</li><li>', $set_of_numbers) . '</li>';
// outputs: <li>1</li><li>2</li><li>3</li>

No looping is necessary.

于 2021-07-30T14:47:05.917 回答
0

Here is answer for your question to get ride of your problem

$Num = '1,2,3,4,5,';
$Array = explode(',',$Num);
foreach ($Array as $Items)
{
echo "<li>&Items</li>"; // This line put put put in the list.
}
于 2017-08-25T06:42:34.727 回答
0

This can easily be achieved by the following code snippet:

<?php
$my_numbers = '1,12,3.2,853.3,4545,221';
echo '<ul>';
foreach(explode(',', $my_numbers) AS $my_number){
    echo '<li>'.$my_number.'</li>';
}
echo '</ul>';

The above code will output the following HTML:

<ul><li>1</li><li>12</li><li>3.2</li><li>853.3</li><li>4545</li><li>221</li></ul>

Credits: http://dwellupper.io/post/49/understanding-php-explode-function-with-examples

于 2017-11-16T11:45:16.320 回答