【问题标题】:Is this the proper way of shift_array and imploding and exploding strings?这是 shift_array 和内爆和爆炸字符串的正确方法吗?
【发布时间】:2014-11-22 23:20:55
【问题描述】:

感谢您的观看,如果这是将一串以逗号分隔的图片链接并将它们转换为图片但将列表分开以显示在网站的不同部分的正确方法,则需要一些建议。

我的代码

<?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;
?>

感谢您即将提出的建议。

【问题讨论】:

  • 感谢您的意见,我将编辑一些内容并让它发挥作用!

标签: php arrays explode implode


【解决方案1】:

我认为您的解决方案非常简单,没有太多不必要的内容。但是请注意,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";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    相关资源
    最近更新 更多