【问题标题】:Why is my foreach loop not looping through and populating array?为什么我的 foreach 循环没有循环并填充数组?
【发布时间】:2015-02-06 16:40:51
【问题描述】:

我有一个类循环遍历一个目录(5 个图像)并将每个图像转换为 base64 格式并填充一个数组。但是,foreach 循环似乎只循环一次。目录中有 5 个图像,因此它应该有 5 次迭代,并且数组也应该是 5 个不同的图像。

PHP

require_once "Results.php";
require_once "ImageHelper.php";

class IntroImageHelper {
    public static function GetImages()
    {
      $results = new Results();
      $results->IntroImages = Array();
      $dir = new DirectoryIterator("img/");
      $ImageExists = false;
      foreach($dir as $file)
      {
        if($file->isFile())
        {
          $ImageExists = $file->__toString();
          break;
        }
      }

      if($ImageExists)
      {
        $tempImage = new Results();
        $tempImage->ImageName = $ImageExists;
        $tempImage->ImageData = ImageHelperIntroSlides::DownloadImage($file);
        array_push($results->IntroImages, $tempImage);
      }

       return $results;
    }
}

输出:

{"IntroImages: [
    {"ImageName": "image.png",
     "ImageDate": "base64imagedata"
    }
  ]
}

【问题讨论】:

  • 你没有在循环内调用array_push()

标签: php arrays foreach


【解决方案1】:

为什么在for循环中有break?这将退出循环...

【讨论】:

  • 这是一个问题,而不是一个答案。
  • 这是一个问答。由于中断,它只通过一次。我试图指出这一点:)
【解决方案2】:

这正是break 会做的事情,它将打破循环。

如果您只需要标记一个值,请删除中断并让迭代继续。

但在您的情况下,您不需要进行检查,将您的循环更改为以下内容:

foreach($dir as $file)
{
    if($file->isFile())
    {
        $tempImage = new Results();
        $tempImage->ImageName = $file->__toString();
        $tempImage->ImageData = ImageHelperIntroSlides::DownloadImage($file);
        array_push($results->IntroImages, $tempImage);
    }
}

【讨论】:

    【解决方案3】:

    使用break 语句将停止循环。您可以使用 continue 跳过当前迭代的其余执行并转到下一个迭代,但在您的情况下,只需省略 break 即可解决您的问题:

    foreach($dir as $file) {
        if($file->isFile()) {
          $ImageExists = $file->__toString();
        }
    }
    

    在你的情况下,你的一堆代码应该在循环之外:

    foreach($dir as $file) {
        if($file->isFile()) {
          $ImageExists = $file->__toString();
        }
        if($ImageExists) {
            $tempImage = new Results();
            $tempImage->ImageName = $ImageExists;
            $tempImage->ImageData = ImageHelperIntroSlides::DownloadImage($file);
            array_push($results->IntroImages, $tempImage);
        }
    }
    

    但是你也可以将这两个语句结合起来:

    foreach($dir as $file) {
        if($file->isFile()) {
            $tempImage = new Results();
            $tempImage->ImageName = $file->__toString();
            $tempImage->ImageData = ImageHelperIntroSlides::DownloadImage($file);
            array_push($results->IntroImages, $tempImage);
        }
    }
    

    【讨论】:

    • 感谢@Scopey!我没有完全理解休息的逻辑。我假设它会暂时停止,运行其余代码,然后返回并完成循环。