将数组作为文件创建日期

时间:2016-04-12 22:37:03

标签: php sorting date glob

所以我有一个文件夹path/to/folder,文件夹中的文件夹和文件夹中的文件等等 - 都在一个文件夹path/to/folder内。我想将所有图像的所有名称(.gif,.png,.jpg,.jpeg等)存储在此文件夹path/to/folder中,如此(我的尝试):

$arr = glob("path/to/folder/*.jpg");//not sure how to specify or "|" here

我还需要与图像相关的日期'元数据(创建日期)如此(参见下面的伪代码):

foreach($arr as $a){
    $date_of_a = function_getting_dates_of_a($a);//filectime?
    $newArr[$date_of_a]=function_getting_names_of_a($a);//names are filtered by a pattern
                      //^^^^^^^^^^^^^^^^^^^^^^^^^^^I've already created this.
}

这样我可以使用不同的使用相同的名称​​值,这将是日期,因此两个同名和相同日期对(或元组)取决于重复的数量)会压缩到一个唯一的名称日期项目。例如,

2016-01-01 => path/to/folder/.../name1.jpg//*duplicate name-date pair
2016-01-02 => path/to/folder/.../name2.jpg
2016-01-01 => path/to/folder/.../name1.jpg//*duplicate name-date pair
2016-01-02 => path/to/folder/.../name1.jpg

会将数组减少到

2016-01-01 => path/to/folder/.../name1.jpg//*only one now
2016-01-02 => path/to/folder/.../name2.jpg
2016-01-02 => path/to/folder/.../name1.jpg

此处/.../表示path/to/folder"中的任意数量的文件夹。我处理的数据意味着2016-01-01 => path/to/folder/.../name1.jpg2016-01-02 => path/to/folder/.../name1.jpg是在不同时间制作的两个相同的对象。最后,我希望能够使用array_count_values计算每个名称的实例数。

ATTEMPT

<?php

    $myArray = glob("path/to/folder/*.jpg");
    foreach($myArray as $item){
        $date = filectime($item);//What if no date? Is that possible?
        if(preg_match('/PATTERN/',$item,$match)==1){
            $newArr[$date]=current($match);
        }
    }
    array_count_values($newArr);
    <!-- CODE TO GRAPH ITEMS BY FREQUENCY-->
?>

1 个答案:

答案 0 :(得分:1)

以下代码应创建一个日期时间键数组:

<?php

$myArray = glob("/*.jpg");
$newArr = array();
foreach($myArray as $item){
    $timestamp = filectime($item);
    if ($timestamp === false) {
        continue;
    }
    $date = new \DateTime();
    $date->setTimestamp($timestamp);
    $formattedDate = $date->format('m-d-Y');
    $newArr[$formattedDate]=$item;
}
array_count_values($newArr);
echo "<pre>";
print_r($newArr);
//<!-- CODE TO GRAPH ITEMS BY FREQUENCY-->

当我在同一天创建多个JPG文件时,这就是打印出来的内容:

Array
(
    [04-12-2016] => sdfdsf.jpg
)

至于递归查找文件,您可以尝试这些我在个人项目中使用过的函数:

function findDirectories($rootPath) {
    $directories = array();
    foreach (glob($rootPath . "/*", GLOB_ONLYDIR) as $directory) {
        $directories[] = $directory;
    }
    return $directories;
}

function findFiles($rootPath, $extension) {
    $files = array();
    foreach (glob($rootPath . "/*.$extension") as $file) {
        $files[] = $file;
    }
    return $files;
}

function findFilesRecursive($rootPath,$extension) {
    $files = findFiles($rootPath,$extension);
    $directories = findDirectories($rootPath);
    if (!empty($directories)) {
        foreach ($directories as $key=>$directory) {
            $foundFiles = findFilesRecursive($directory,$extension);
            foreach ($foundFiles as $foundFile) {
                $files[] = $foundFile;
            }
        }
    }
    return $files;
}