dounie0889 2011-11-07 11:24
浏览 38
已采纳

PHP数组 - 删除逗号,If else语句

I am relatively new to arrays, and struggling with the amount of information out there to solve my problem succinctly. This is as far as I have progressed.

My code:

<?php 

$imagearrdisplay = ",8,7,22,";

$displayitem = explode(",", $imagearrdisplay);

for($i = 0; $i < count($displayitem); $i++){

echo "
<div class='banner'><img src='/images/transitions/$displayitem[$i].jpg' /></div>
Count: $i = $displayitem[$i] ";

}

?>

It currently returns a result of:

<div class='banner'><img src='/images/transitions/.jpg' /></div>
Count: 0 =  
<div class='banner'><img src='/images/transitions/8.jpg' /></div>
Count: 1 = 8 
<div class='banner'><img src='/images/transitions/7.jpg' /></div>
Count: 2 = 7 
<div class='banner'><img src='/images/transitions/22.jpg' /></div>
Count: 3 = 22 
<div class='banner'><img src='/images/transitions/.jpg' /></div>
Count: 4 =  

What I would like to achieve is the following:

  1. To remove the first and last comma within the imagearraydisplay when it explodes so that I do not end up with a blank image at the beginning and end.

  2. Randomise the results of the array

  3. Perform an if / else function to find the [0] and adjust the first result so that I can use css to style the image accordingly.

To be able to then produce an outcome that looks like:

<div class='firstbanner'><img src='/images/transitions/22.jpg' /></div>
<div class='banner'><img src='/images/transitions/7.jpg' /></div>
<div class='banner'><img src='/images/transitions/8.jpg' /></div

I know it's possible, though struggling through the maze of tutes out there. Any help would be really appreciated.

  • 写回答

6条回答 默认 最新

  • dtkjthe4025 2011-11-07 11:30
    关注

    Try with:

    $imagearrdisplay = trim(',8,7,22,', ',');
    $displayitem = explode(',', $imagearrdisplay);
    shuffle($displayitem);
    

    To check if element is first just do:

    if ( $i == 0 ) {}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程