Php 检查foreach语句返回的数组的值

Php 检查foreach语句返回的数组的值,php,Php,这是我的密码: <?php $class = array(); /*$class = array_reverse($class_model, false);*/ $cycle = 199 ; $i= 0; $contentdirectory = 'DEADWAVE_proj_dir/DEAD-WAVE_content/'; $contentlaunch = scandir($contentdirectory); natsort($contentlaunch);

这是我的密码:

<?php

$class = array();
/*$class = array_reverse($class_model, false);*/

$cycle = 199 ;
$i= 0;

$contentdirectory = 'DEADWAVE_proj_dir/DEAD-WAVE_content/';     
$contentlaunch = scandir($contentdirectory);
natsort($contentlaunch);        
$id = count($contentlaunch); 

foreach ( $contentlaunch as $value )
{ 
  if ( preg_match("/.png",$value)
       || preg_match("/.jpg",$value)
       || preg_match("/.gif",$value) )
   {
    echo '<a id="'.--$id.'"target="_blank" href="">
       <img  class="'.$class[ $i % $cycle ].'"
       src="DEADWAVE_proj_dir/DEAD-WAVE_content/'.$value.'"/></a>';
    ++$i;
   }
 } 
?>

这根本不起作用,问题是为什么


我设想,检查文件类型和echo img标记,只检查那些作为图像的数组值,避免目录中的非图像文件。我对所有解决方案都持开放态度。

要确定文件是否为图像,您可以使用:

// $path = 'somepath';
// $filename = 'somefile';
$finfo = new finfo();
$currentFileMimeType = $finfo->file($path . $filename, FILEINFO_MIME_TYPE);
if('image' == array_shift((explode('/', $currentFileMimeType))))
{
    // echo images
}

您的正则表达式模式将不起作用。例如,/.png应该是/\.png/

但是,您可以不使用regex,而只使用函数,该函数将为您提供给定路径的文件扩展名

$info = pathinfo($value);
$extension = $info['extension'];
if (in_array($extension, array('png', 'jpg', 'gif')) {
  ..

最后,我不确定所有的$class/$cycle东西…

这个例子相当混乱。我不完全明白它想做什么。在循环中,您将递减$i,然后在下一条语句中递增它。你为什么要这样做?类数组是空的,并且你的行格式很难理解,请尽量使你的代码清晰简洁,以便我们更好地帮助你。
<?php

$class = array();

$class = array_reverse($class_model, false);
$cycle = 199 ;
$i = 0;

$contentdirectory = 'DEADWAVE_proj_dir/DEAD-WAVE_content/'; 
$contentlaunch = scandir($contentdirectory);

natsort($contentlaunch);
foreach ( $contentlaunch as $id => $value ) 
{   
    if ( preg_match("/(\/.png|\/.jpg|\/.gif)/",$value) ) 
    {
        echo '<a id="'.$id.'" target="_blank" href=""><img class="'.$class[ $i++ % $cycle ].'"  src="DEADWAVE_proj_dir/DEAD-WAVE_content/'.$value.'"/></a>';  
    } 
} 
?>
if ( in_array(pathinfo($value, PATHINFO_EXTENSION), array('jpg', 'gif', 'png')) ) { ...