从 1 个目录获取文件并读取另一个目录中的文件,而不是将文件与文件内容进行匹配
Get files from 1 directory and read files in another, than match files with file contents
为了解释我的意思,我有 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;
}
?>
分步解决方案:
- 您需要从您拥有图像的文件夹中获取图像:
$temporaryImageArray = scandir($_SERVER['DOCUMENT_ROOT'].'/img/gallery/');
- 您需要从您拥有文本文件的文件夹中获取文本文件:
$temporaryTextArray = scandir($_SERVER['DOCUMENT_ROOT'].'/img/gallery
/数据/');
- 两个临时数组都可能包含不必要的元素,例如子目录。例如,您的图像文件夹包含无用的数据子目录。所以需要准备有用的图像数组子集:
$images = array();
foreach ($temporaryImageArray as $temporaryImage) {
if (is_file($_SERVER['DOCUMENT_ROOT'].'/img/gallery/'.$temporaryImage)) {
$images[]=array("imgSrc" => $_SERVER['DOCUMENT_ROOT'].'/img/gallery/'.$temporaryImage);
}
}
- 并准备有用的课文子集:
$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));
}
}
- 最后,搜索匹配项:
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"
元素,它将保存一组匹配的文本文件名。
基于文本文件与图像同名这一事实,我使用了一种略有不同的方法。
通过将代码封装在一个函数中来编辑原始代码,因此现在您可以调用该函数并处理它的 return 值。
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 />';
}
}
为了解释我的意思,我有 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;
}
?>
分步解决方案:
- 您需要从您拥有图像的文件夹中获取图像:
$temporaryImageArray = scandir($_SERVER['DOCUMENT_ROOT'].'/img/gallery/');
- 您需要从您拥有文本文件的文件夹中获取文本文件:
$temporaryTextArray = scandir($_SERVER['DOCUMENT_ROOT'].'/img/gallery
/数据/');
- 两个临时数组都可能包含不必要的元素,例如子目录。例如,您的图像文件夹包含无用的数据子目录。所以需要准备有用的图像数组子集:
$images = array();
foreach ($temporaryImageArray as $temporaryImage) {
if (is_file($_SERVER['DOCUMENT_ROOT'].'/img/gallery/'.$temporaryImage)) {
$images[]=array("imgSrc" => $_SERVER['DOCUMENT_ROOT'].'/img/gallery/'.$temporaryImage);
}
}
- 并准备有用的课文子集:
$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));
}
}
- 最后,搜索匹配项:
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"
元素,它将保存一组匹配的文本文件名。
基于文本文件与图像同名这一事实,我使用了一种略有不同的方法。
通过将代码封装在一个函数中来编辑原始代码,因此现在您可以调用该函数并处理它的 return 值。
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 />';
}
}