PHP - Create unique id number for each item

953 views Asked by At

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

There are 1 answers

3
M H On BEST ANSWER
<?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++;
} ?>