简体   繁体   English

PHP中while循环的替代方法

[英]Alternative to a while loop in PHP

I am trying to develop my understanding of php and would really appreciate any help. 我正在努力发展对php的理解,并且非常感谢任何帮助。 I have used a while loop to compare some values posted in my form with what is stored in a csv file. 我使用了while循环将表单中发布的某些值与csv文件中存储的值进行比较。 This code works well. 此代码运行良好。 However, is it possible to achieve the same result using a FOR EACH loop or even a Do Until?? 但是,是否可以使用FOR EACH循环甚至执行直到操作来获得相同的结果? Or both?? 或两者?? Many thanks for any support 非常感谢您的支持

$file_handle = fopen("games.csv", "r"); # identify which file is being used.
while(!feof($file_handle))
{
$gameinfo = fgetcsv($file_handle);
if ($gameinfo[0] == $_POST["gameID"])
{
$GameName = "$gameinfo[2]";
$GameCost = "$gameinfo[4]";
$GameFound = true;
}
}
fclose($file_handle);

while is the best suited statement for this task, because you want to check for EOF before doing any read. while是最适合此任务的语句,因为您需要在进行任何读取之前检查EOF

You can transform it in a do-while (there is no do-until in PHP) as an exercise: 您可以在变换它do-while (没有do-until在PHP)作为一个练习:

do
{
   if (!feof($file_handle))
   {
      $gameinfo = fgetcsv($file_handle);

      if ($gameinfo[0] == $_POST["gameID"])
      {
         ...
      }
   }
}
while(!feof($file_handle));

or shorter 或更短

do
{
   if (feof($file_handle))
      break;

   $gameinfo = fgetcsv($file_handle);

   if ($gameinfo[0] == $_POST["gameID"])
   {
      ...
   }
}
while(true);

but that's just a bad way to write a while . 但这只是写while的坏方法。

Regarding foreach , quoting the doc 关于foreach ,引用文档

The foreach construct provides an easy way to iterate over arrays. foreach构造提供了一种迭代数组的简便方法。 foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. foreach仅适用于数组和对象,当您尝试对具有不同数据类型的变量或未初始化的变量使用它时,将发出错误。

You can customize iteration over objects , this let you ( Warning , layman language) use foreach on "custom objects" so that you can, in a way, extend the functionality of foreach . 您可以自定义对象的迭代 ,这使您( 警告 ,通俗的语言)可以在“自定义对象”上使用foreach ,以便您可以通过某种方式扩展foreach的功能。
For example to iterate over CSV files you can use this class 例如,要遍历CSV文件,您可以使用此类

<?php
class FileIterator implements Iterator
{
    private $file_handle = null;
    private $file_name;
    private $line;

    public function __construct($file_name)
    {
        $this->file_name = $file_name;

        $this->rewind();
    }

    public function rewind()
    {
        if (!is_null($this->file_handle))
            fclose($this->file_handle);

        $this->line = 1;
        $this->file_handle = fopen($this->file_name, "r");
    }

    public function current()
    {
        return fgetcsv($this->file_handle);
    }

    public function key() 
    {
        return $this->line;
    }

    public function next() 
    {
        return $this->line++;
    }

    public function valid()
    {
        $valid = !feof($this->file_handle);

        if (!$valid)
           fclose($this->file_handle);

        return $valid;
    }

}
?>

and use it this way 并以这种方式使用

$it = new FileIterator("game.csv");

foreach ($it as $line => $gameObj) 
{
    echo "$line: " . print_r($gameObj, true) . "<br/>";
}

Which produce something like 产生类似

1: Array ( [0] => 0 [1] => Far Cry 3 ) 
2: Array ( [0] => 1 [1] => Far Cry Primal ) 
3: Array ( [0] => 2 [1] => Alien Isolation )

for this file 为此文件

0,Far Cry 3
1,Far Cry Primal
2,Alien Isolation

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

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