稍后在程序中使用数组会导致仅显示一条记录


Using an array later in a program results in only displaying one record

我觉得问这个很傻,我相信这是非常简单的事情。当我稍后尝试在脚本中引用变量"test"时,它不会列出数组中的所有 70 个项目,而是只列出一个。

<?php
$exclude = '/^.*'.(lck)$/i'; 
$directory = 'images/slide/';   
$rootpath = 'images/slide/';
$pathnames = preg_grep('/^([^.])/', scandir($rootpath));
shuffle($pathnames);
foreach ($pathnames as $pathname) {
    if (preg_match($exclude, $pathname)) {
      } else {
        $test = '["'.$directory. $pathname.'"]';    
     }
    }
?>

如果我在测试变量声明下方回显"test",它会正确显示所有内容。如果我稍后回显它,它只显示一个项目。

看起来您正在将测试视为字符串,尝试在代码开头添加以下内容:

$test = array();

然后更改:

$test = '["'.$directory. $pathname.'"]';   

自:

$test[] = $directory. $pathname;   

在循环的每次迭代中,您都会覆盖先前分配的值 $test ;

$test = '["'.$directory. $pathname.'"]';

显示此值时,无论是在分配后还是在循环之后,您都将获得最后一个分配的值。 如果要累积变量中的值,则需要附加到它,例如,

$test .= '["'.$directory. $pathname.'"]';

或者,如果您希望$test是一个数组并包含其中的所有文件,那么您的赋值应该是数组元素,而不是整个变量,例如

$test[] = '"'.$directory. $pathname.'"';