【问题标题】:Get files from 1 directory and read files in another, than match files with file contents从 1 个目录获取文件并读取另一个目录中的文件,而不是匹配具有文件内容的文件
【发布时间】:2015-07-25 10:51:00
【问题描述】:

为了解释我的意思,我有 1 个包含图像的目录。我有另一个包含有关图像信息的文本文件。我想要一个数组,每个图像与另一个包含其数据的数组相匹配。

试图解决这个问题我的脑袋开始爆炸,而我对 PHP(尤其是数组)的了解非常少。如果有人可以帮助解决我到目前为止所遇到的问题,或许可以帮助解释正在发生的事情(或将我指向一个解释的网站),我将非常感激。

到目前为止,这是我的代码:

<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
ini_set('display_errors',1);

function loadImages()
{
  $images=array();

  if ($handle = opendir($_SERVER['DOCUMENT_ROOT'].'/img/gallery')) {

     $imageData = loadImageData();

      $count = 0;
      while (false !== ($entry = readdir($handle))) {

          if ($entry != "." && $entry != "..") {
              if((end(explode(".", $entry)) == "jpg") || (end(explode(".", $entry)) == "jpeg") || (end(explode(".", $entry)) == "JPG") || (end(explode(".", $entry)) == "gif") || (end(explode(".", $entry)) == "png")) {
                $images[$imagedata[$count]] = $entry;
                $count += 1;
              }
          }
      }

  }
        var_dump($images);

      closedir($handle);
      return $images;
}

function loadImageData()
{
  $imageData=array();

  if ($handle = opendir($_SERVER['DOCUMENT_ROOT'].'/img/gallery/data/')) {

      $count = 0;
      while (false !== ($entry = readdir($handle))) {

          if ($entry != "." && $entry != "..") {
              if(end(explode(".", $entry)) == "txt") {
                $path = $_SERVER['DOCUMENT_ROOT'].'/img/gallery/data/';

                $file = fopen($path.$entry, "r") or die("Something went wrong gathering photo information. I suggest you contact the server admin about this.");
                $fileData = array();

                $line = 0;
                while(! feof($file)) {
                  $lineData = fgets($file);

                  $lineData = str_replace("\n", "", $lineData);
                  $lineData = str_replace("\r", "", $lineData);

                  $fileData[$line] = $lineData;
                  $line++;
                }

                fclose($file);

                $imageData[$count] = $fileData;
                $count += 1;
              }
          }
      }
  }

  closedir($handle);
  return $imageData;
}
?>

【问题讨论】:

  • 文件名是否相关 - 即 img1.jpg 和 img1.txt?
  • @RamRaider 是的,他们有,忘记提了。

标签: php arrays file directory readdir


【解决方案1】:

基于文本文件与图像命名相同的事实,我使用了稍微不同的方法。

通过将代码封装在函数中来编辑原始代码,因此现在您可以调用该函数并处理它的返回值。

    function get_gallery_images(){

        /*

        */
        $imgdir=$_SERVER['DOCUMENT_ROOT'].'/img/gallery';
        $extns=array('jpg','jpeg','png','gif');
        $output=array();



        /*
            Could have done this without the recursive iterators but... 
        */
        foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $imgdir, RecursiveDirectoryIterator::KEY_AS_PATHNAME), RecursiveIteratorIterator::CHILD_FIRST ) as $file => $info ) {
            if( $info->isFile() ){

                $ext=strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
                $name=pathinfo( $file, PATHINFO_FILENAME );

                /* Only get images that have correct extension */
                if( in_array( $ext, $extns ) ) {

                    /* As data and image have the same name - we can deduce a filename */
                    $textfile=$imgdir . '/data/' . $name . '.txt';

                    /* Get image properties */
                    list( $width, $height, $type, $attr ) = getimagesize( $file );

                    /* If the text file does exist, add this image and associated data & properties to the output array */
                    if( file_exists( $textfile ) ){
                        clearstatcache();
                        $output[ $name ]=array( 'path' => $info->getPath(), 'data'=>file_get_contents( $textfile ), 'width'=>$width, 'height'=>$height, 'size'=>filesize( $file ) );
                    }
                }
            }
        }
        /* Process the output array in whatever whay you see fit */
        return $output;
    }


    /* Call the function */
    $output = call_user_func( 'get_gallery_images' );

    if( !empty( $output ) ){
        /* do whatever processing you require */
        foreach( $output as $key => $arr ){
            echo $key.' '.$arr['data'].'<br />';
        }
    }

【讨论】:

  • 工作正常,很容易看到发生了什么,谢谢。
  • 好 - 很高兴它有帮助。您可以取消 getimagesize() 和 filesize() 调用以加快速度
  • 我只是看着那些,想知道他们为什么在那里。我会这样做的,谢谢。
  • $output返回到另一个php文件只是返回一个空数组。有什么想法吗?
  • 你是什么意思?您是否尝试使用不同的脚本或其他方式处理 $output 数组?
【解决方案2】:

分步解决方案:

  1. 您需要从您拥有图片的文件夹中获取图片:

$temporaryImageArray = scandir($_SERVER['DOCUMENT_ROOT'].'/img/gallery/');

  1. 您需要从您拥有文本文件的文件夹中获取文本文件:

$temporaryTextArray = scandir($_SERVER['DOCUMENT_ROOT'].'/img/gallery/data/');

  1. 两个临时数组都可能包含不必要的元素,例如子目录。例如,您的图像文件夹包含数据子目录,这是无用的。所以你需要准备图像数组的有用子集:

$images = array(); foreach ($temporaryImageArray as $temporaryImage) { if (is_file($_SERVER['DOCUMENT_ROOT'].'/img/gallery/'.$temporaryImage)) { $images[]=array("imgSrc" => $_SERVER['DOCUMENT_ROOT'].'/img/gallery/'.$temporaryImage); } }

  1. 并准备有用的文本子集:

$texts = array(); foreach ($temporaryTextArray as $temporaryText) { if (is_file($_SERVER['DOCUMENT_ROOT']. '/img/gallery/data/'.$temporaryText)) { $texts[]=array("name" => $_SERVER['DOCUMENT_ROOT']. '/img/gallery/data/'.$temporaryText, "content" => file_get_contents($_SERVER['DOCUMENT_ROOT'].'/img/gallery/data/'.$temporaryText)); } }

  1. 最后,搜索匹配项:

foreach ($images as $imageKey => $imageValue) { $imageContent = file_get_contents($imageValue["imgSrc"]); $images[$imageKey]["matches"] = array(); foreach ($texts as $text) { if (file_get_contents($text["content"]) === $imageContent) { $images[$imageKey]["matches"][]=$text["name"]; } } }

请注意,该解决方案根本不假设存在匹配,如果存在匹配,则它是唯一的。但是,测试的负担留给您,如果您有任何问题,请随时告诉我。目的是有一个 $images 数组,它将保存数组,有一个 "imgSrc" 元素和一个 "matches" 元素,它将保存匹配的文本文件名集。

【讨论】:

  • 谢谢,我现在就开始尝试,如果有任何问题,我会回复您。
  • 我不想听起来很愚蠢,但$images 是否应该仅包含此代码的任何内容?我得到的只是array(0) { }。另外,请注意,在 file_get_contents 上,您使用方括号而不是普通方括号。
  • 正如我已经提到的,代码没有经过测试。在 file_get_contents 确实有一个方括号。这是一个错字。只要您的图像文件夹包含任何图像,$images 就不应为空。 $temporaryImageArray 将是一个包含指定路径的文件名的数组。 $images 开始是一个空数组,但是遍历 $temporaryImageArray 之后,它应该包含一些元素。
  • 我在每个目录中添加了斜杠,现在它有点工作了。 file_get_contents 好像在找内容的内容,不过我从这里应该没问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-18
  • 1970-01-01
相关资源
最近更新 更多