Explode to array and print each element as list item

前提是你 提交于 2019-12-21 02:55:07

问题


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.


回答1:


$numbers = '1,2,3';

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

foreach ($array as $item) {
    echo "<li>$item</li>";
}



回答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...



回答3:


$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>



回答4:


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.
}



回答5:


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



来源:https://stackoverflow.com/questions/16257063/explode-to-array-and-print-each-element-as-list-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!