phparrayssplitzipfilenames

PHP:: Selectively pack zip-archives from files in folder


I have a folder containing a few hundred files. The filename is always similiar to ######_### - #######.ext What they all have in common is the delimiter " - ". Files with the same name prior to the delimiter should be regarded as the same article group.

What I want to achieve is to run a php-file that scans the entire folder and creates zip-archives from those files. Each archive should contain all files from one article group and be named like the filename prior to the delimiter to know about its content.

Example (filenames; yes, they may have whitespace):

After running the process there should be 2 archives (in this case). One named Article_1.zip containing the first two files as they form a group. The second file containing the remaining three files and named Article_2.zip as they form a group.

I fiddled around half the day with array_count_values, array_key_exists and more, but I'm stuck at that point. Besides I'm sure that my approach to get the part prior to the delimiter as filename is already way complicated and overdone.

I'd greatly appreciate any help! :)


Solution

  • php code to separate files based on article name is as follows:-

    <?php
    $array = Array('Article_1 - Subtype a.ext','Article_1 - Subtype b.ext','Article_2 - Subtype a.ext','Article_2 - Subtype b.ext','Article_2 - Subtype c.ext');
    $new_array = array(); 
    foreach($array as $arr) { 
        $exploded_array = explode("-", $arr); 
        $new_array[$exploded_array[0]][] = $arr; 
    }
    echo "<pre/>";
    print_r($new_array);
    ?>
    

    Output:- https://3v4l.org/5ScBG