这是shift_array和爆炸和爆炸字符串的正确方法吗?

时间:2014-11-22 23:20:56

标签: php arrays explode implode

感谢您查看,只需要一些建议,如果这是一个正确的方法,将一个完整的图像链接分隔为逗号并将其转换为图像,但将列表分开显示在网站的不同部分。

我的代码

<?php
//the array, will be grabbing from database soon
$string = "main.jpg,extra_img_1.jpg,extra_img_2.jpg,extra_img_3.jpg,extra_img_4.jpg,extra_img_5.jpg";

//explode the whole array
$array = explode(',',$string);

//remaking the list turning it back into an array
$oldstring = '<li>'.implode('</li><li>',$array).'</li>';

// removing the first string in the commad array
array_shift($array);

//turning it back into an array without the first listed item
$newstring = '<li>'.implode('</li><li>',$array).'</li>';

//showing the old string in a listed format
echo $oldstring;

echo '<hr>';
// showing the first item in the old string
echo '<li>'.explode(',', $string)[0].'</li>';
echo '<hr>';

//once its shifted, i want to reshow the list
echo $newstring;
?>

感谢即将到来的建议。

1 个答案:

答案 0 :(得分:0)

我认为你的解决方案非常简单,没有多少是不必要的。但请注意,array_shift()返回已移位的元素。第二次没有必要explode()[0]

// Linebreaks added to make the output readable

$string = "main.jpg,extra_img_1.jpg,extra_img_2.jpg,extra_img_3.jpg,extra_img_4.jpg,extra_img_5.jpg";

$array = explode(',',$string);
$oldstring = '<li>'.implode("</li>\n<li>",$array)."</li>\n";

$s0 = array_shift($array);
$newstring = '<li>'.implode("</li>\n<li>",$array)."</li>\n";

echo $oldstring;
echo "<hr>\n";
echo "<li>$s0</li>\n";
echo "<hr>\n";
echo $newstring;

就个人而言,我可能只是循环遍历元素:

$string = "main.jpg,extra_img_1.jpg,extra_img_2.jpg,extra_img_3.jpg,extra_img_4.jpg,extra_img_5.jpg";

$array = explode(',',$string);
foreach ($array as $s)
  echo "<li>$s</li>\n";
echo "<hr>\n";

$s0 = array_shift ($array);
echo "<li>$s0</li>\n";
echo "<hr>\n";
foreach ($array as $s)
  echo "<li>$s</li>\n";