donglou8371 2015-06-08 22:45
浏览 17
已采纳

PHP - 为每个项目创建唯一的ID号

I have an image array loop, and it successfully loops through my image items. However, I need to give the 'data-slide-index' attribute for each item a unique number, starting from 0, adding 1 for each following item (0 - 9 if there are ten images in total). I realize this is probably simple stuff but I am a PHP newbie so would really appreciate a tip of about the best, simplest way to do this.

<?php $images = get_post_meta(get_the_ID(), "images", true);
$images = unserialize($images);

foreach($images as $image) {
    $ar[] = array("order" => $image['order'], "img_id" => $image['image_id'], "desc" => $image["desc"]);
}

asort($ar);

foreach($ar as $item) {

    $image_id = $item['img_id'];
    $media_med = wp_get_attachment_image_src( $image_id, "medium", false);
    $media_full = wp_get_attachment_image_src( $image_id, "full", false);

    echo "<a data-slide-index='" . $count ."' href=''><img data-title='" . $item["desc"] . "' data-big='". $media_full[0] . "' src='" . $media_med[0] . "'></a>";
} ?>
  • 写回答

1条回答 默认 最新

  • dsfew215211 2015-06-08 22:49
    关注
    <?php $images = get_post_meta(get_the_ID(), "images", true);
    $images = unserialize($images);
    
    foreach($images as $image) {
            $ar[] = array("order" => $image['order'], "img_id" => $image['image_id'], "desc" => $image["desc"]);
        }
    
        asort($ar);
    //Create count variable
    $i=0;    
    foreach($ar as $item) {
    
    $image_id = $item['img_id'];
    $media_med = wp_get_attachment_image_src( $image_id, "medium", false);
    $media_full = wp_get_attachment_image_src( $image_id, "full", false);
    
     //assign the number to the slide index
     echo "<a data-slide-index='".$i."' href=''><img data-title='" . $item["desc"] . "' data-big='". $media_full[0] . "' src='" . $media_med[0] . "'></a>";
    
    //plus up the variable for each loop item
    $i++;
    } ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?