繁体   English   中英

PHP计算for循环中if条件语句的值

[英]PHP count values of an if conditional statement within a for loop

我有一个PHP代码,看看是否存在一个或多个图片。 如果图片存在,我想计算它们并回答答案。 这是我的代码:

<?php
//Start Pictures section - dictates that if there are pictures this section is shown - if not this section is now shown.
for ($x=1; $x<=21; $x++)  {
    if($x<=9) {
        $picValue = 'picture0'.$x;
    }
    else {
        $picValue = 'picture' . $x;
    }

    $imageURLpixel = ABSOLUTE_URL_IMG.$code.'/pixel/'. $picValue .'.jpg';

    //Check if the image exists or not
    $pictureCount = 1;
    if (@fopen($imageURLpixel,'r')) {
    $pictureCount++;    
    $pictureCounter = count($pictureCount);
    }

 echo $pictureCounter;

} 

?>

我的示例中有3张图片,输出为111111111111111111111 - 我的输出为3 我的错误日志中没有出现任何错误。

只是为了说清楚。 解决方案是直到这一个都在修复代码的“一些问题”,但不是全部在一起。

这是我的方法,使其清晰,易懂和可读 - 也许是一些学习曲线等。

$baseUrl = ABSOLUTE_URL_IMG.$code.'/pixel/';
$pictureCount = 0;

// for the first 20 pictues
for ($x=0; $x<21; $x++)  {
      // make it more readable and practical - see "sprintf"-documentation.
      $filename = sprintf('picture%02d.jpg', $x+1); // < is "one-based index"

      $fileUrl = $baseUrl . $filename;

      // if url exists, increase counter;
      if (@fopen($fileUrl,'r')) 
            $pictureCount++;

 }
 // total count of existing images.
 echo $pictureCount; 
$pictureCount++;    
$pictureCounter = count($pictureCount);

上面的第一行包含找到的图片数量。 所以你不需要做任何其他的事情来获得那个使得下一行不必要的计数。 这很重要,因为你错误地使用了count() count()用于计算数组中元素的数量。 $pictureCount 不是数组。

此外,您应该将$pictureCount初始化为零,除非您知道已经有一个图像占用。 否则你的总数将被夸大一个。

此外,您初始化$pictureCount并在循环内回显它。 这两个部分都需要在你的循环之外。

更正代码:

$pictureCount = 0;
for ($x=1; $x<=21; $x++)  {
    if($x<=9) {
        $picValue = 'picture0'.$x;
    } else {
        $picValue = 'picture' . $x;
    }

    $imageURLpixel = ABSOLUTE_URL_IMG.$code.'/pixel/'. $picValue .'.jpg';

    //Check if the image exists or not
    if (@fopen($imageURLpixel,'r')) {
      $pictureCount++;    
    }
} 
echo $pictureCount;

1,看看我对你的问题的评论。 你不想count() $pictureCount

2,你在for循环中回应。 count($pictureCount)总是输出1,但在你的情况下,每次你的for循环迭代。 尝试更像这样的代码:

$pictureCount = 1;
for ($x=1; $x<=21; $x++)  {
    if($x<=9) {
        $picValue = 'picture0'.$x;
    } else {
        $picValue = 'picture' . $x;
    }

    $imageURLpixel = ABSOLUTE_URL_IMG.$code.'/pixel/'. $picValue .'.jpg';

    //Check if the image exists or not
    if (@fopen($imageURLpixel,'r')) {
        $pictureCount++;
    }
}

echo $pictureCount; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM