开发者

Problem on adding a counter to a code with 3 foreach loops

开发者 https://www.devze.com 2023-02-19 18:38 出处:网络
I am having trouble on adding a counter starting from 1 to the following piece of code, near echo $images;

I am having trouble on adding a counter starting from 1 to the following piece of code, near echo $images; I would like to count how many times it echoes $images. My purpose i to add the number next to images. Any help would be great! Please have in mind if there is a way of making the following code better. Thank you!

foreach($items as $item) {
    $descr = $xPath->query('./description', $item);

    foreach ($descr as $d) {

        $temp_dom = new DOMDocument();
        $temp_dom->loadHTML( $d->nodeValue );
        $temp_xpath = new DOMXPath($temp_dom);
        $img = $temp_xpath->query('//div[@class="separator"]//img');

 foreach ($img as $imgs) {   
$images=$imgs->getAttribute('s开发者_StackOverflowrc'); 
echo $images; }

   }

}


Initialize a variable, e.g. $count = 0;, and then add 1 on each loop:

 foreach ($img as $imgs) {   
$images=$imgs->getAttribute('src'); 
++$count; // <= here you go
echo $images; }


foreach don't maintain its own counter, if you want a counter you can use the for loop instead

for ($i = 0; $i <= count($img).; $i++) {
    $images = $img[i]->getAttribute('src');
    echo $images;
}

Or you can just initialize your own counter in the foreach

foreach($img as $imgs) {
$i = 1;
$images = $imgs->getAttribute('src');
echo $images;
$i++;
}


Can't you just add something like

$counter = 0;

before the firsrt foreach, and then somethin like

$counter++;
echo $images;
echo $counter;

just increase counter at same time, you echo $images. Or am I missing something?

0

精彩评论

暂无评论...
验证码 换一张
取 消