【问题标题】:How to make and call a function if it has a loop inside of it?如果函数内部有循环,如何创建和调用函数?
【发布时间】:2015-04-03 05:02:04
【问题描述】:

我有一个用于显示数组内所有图像的 for 循环。我怎样才能把它放在一个函数中,所以当我需要它时,我可以调用它,它会显示所有的图片?

$countArray = count($fil[0]);

function displayAllImages(){
for ($x=0; $x<$countArray; $x++){
    echo '<img src="photos/'.$fil[0][$x].'" /><br />';
}
}
displayAllImages(); //nothing shows up

【问题讨论】:

  • 这是基本的 PHP 使用 $counTArray, $fil 作为参数
  • 使用$fil作为参数并在函数中使用foreach。不需要$countArray
  • 或者使用glob()并过滤特定的图像文件扩展名。否则,如果您有除图像文件以外的任何内容,它们也会显示这些文件。
  • 不管里面有没有循环,调用函数就像调用函数一样。但是你需要学会正确缩进,这样你就可以一眼看出括号是用于循环还是函数。
  • 也请使用foreach

标签: php arrays function for-loop


【解决方案1】:

由于您在函数外部声明了 $fil 和 $countArray,因此您无法访问它们,因此您应该将数组作为函数参数传递

function displayAllImages($images){
  $counter = count($images[0]);
  for ($x=0; $x < $counter; $x++){
      echo '<img src="photos/'.$images[0][$x].'" /><br />';
  }
}
displayAllImages($countArray, $fil); //now it will show up

使用 foreach 循环执行此操作的最佳方法可能如下:

function displayAllImages($imagesSources){
  foreach($imagesSources as $value){
    echo '<img src="photos/'.$value.'" /><br />';
  }
}

$images = array("image1.png", "image2.png", "image3.png");
displayAllImages($images);

$images = array("0" => array("image1.png", "image2.png", "image3.png"));
//in this case you can pass directly $images[0] to the function as pointed in the comments
displayAllImages($images[0]);

正如 cmets 所指出的,看看 php 变量范围 HERE

【讨论】:

  • 这是完全错误的!你没有在函数中使用$counter$array 是一个数组而不是一个值
  • 你能缩进这个吗?您可能需要在for 循环中使用count($array)(正如马里奥指出的那样,foreach 无论如何都会更好)。
  • 您只需将$fil 传递到函数中。 count() 可以很容易地从 $fil 计算出来 - 但无论如何你都不需要计数 - 只需使用 foreach() 来遍历数组。
  • 真正要成为一个答案,而不仅仅是“来,这里有一些代码”,您至少需要稍微解释一下变量范围。真的,这个问题应该已经关闭或标记为可变范围问题的重复。
  • 你永远不应该简单地调用一个变量$array - 给它一个有意义的名字,就像你把你的外部数组命名为$images...foreach ($images as $filename) - 任何使它更容易阅读的东西,当代码变大等时,进一步减少错误。
【解决方案2】:

原因是,您在函数内部使用了未声明的变量 激活 error_reporting,PHP 应该注意,$countArray 没有被声明。

2 种可能性:

将数组作为参数赋予函数:

// $fil[0] is an array

function displayAllImages($a)
{
    if(is_array($a)) foreach($a as $i => $v)
    {
        echo '<img src="photos/'.$v.'" /><br />';
    }
}
displayAllImages($fil[0]);

或者你在函数内部告诉 PHP,你想在函数外部使用一个变量:

// $fil[0] is an array

function displayAllImages()
{
    global $fil;
    if(is_array($fil[0])) foreach($fil[0] as $i => $v)
    {
        echo '<img src="photos/'.$v.'" /><br />';
    }
}
displayAllImages();

请看http://php.net/manual/en/language.variables.scope.php

【讨论】:

  • 只是为了强调在函数内部引用全局变量不是首选方式。 (global $fill - 只能是一个l
  • 即使为此目的,我认为最好传递一个引用,但起初他会想到变量范围;)
  • 这里不需要通过引用。数组没有被改变。 (PHP 实现了写时复制。)
猜你喜欢
  • 2021-09-08
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 1970-01-01
  • 2020-11-27
  • 2015-05-11
  • 2020-06-05
  • 1970-01-01
相关资源
最近更新 更多