简体   繁体   中英

PHP: how to create an array of an array of files (aka, an array of scandir)

I'd like to loop through 4 paths, and for each path store that specific path's files in an array. The reason is, I'd like to insert each file title and file path in a database.

So:

$COMICS_path = array('./images/Comics/Charts/', './images/Comics/Life/', './images/Comics/Misc/', './images/Comics/Office/', './images/Comics/Political/');

$COMICS_files = array(scandir('./images/Comics/Charts/'), scandir('./images/Comics/Life/'), scandir('./images/Comics/Misc/'), scandir('./images/Comics/Office/'), scandir('./images/Comics/Political/'));

$COMICS_path seems to output the correct array.

but, $COMICS_files just outputs "ARRAY", when I'm expecting something like:

$COMICS_files = (file1.png, file2.png, file3.png, ... file n.png)

Is this possible? If not, can anyone direct me to the best way to loop through several folders and retrieve each file?

Thanks!

$COMICS_files = array();
foreach($COMICS_path as $path)
    $COMICS_files = array_merge($COMICS_files, scandir($path));
var_dump($COMICS_files);

Since scandir() returns an array, you would have to merge them together into one big array.

It's outputting a 2 dimensional array because scandir returns an array.

So $COMICS_files[0] will be (afile1.png, afile2.png, ...) and $COMICS_FILES[1] will be (bfile2.png, bfile2.png)

If you want all of these files in a single array you should do something like so

$COMICS_path = array('./images/Comics/Charts/', './images/Comics/Life/', './images/Comics/Misc/', './images/Comics/Office/', './images/Comics/Political/');
$COMICS_files = array();

$COMICS_path_sz = count($COMICS_path);
for ($i = 0; $i < $COMICS_path_sz; ++$i) {
    $tmp_arr = scandir($COMICS_path[i]);
    if ($tmp_arr !== FALSE) {
        $COMICS_files = array_merge($COMICS_files, $tmp_arr);
    }
}

First of all, we need to sort out what is the "output" you are referring to. If you refer to the results of echo, then the expected result is "ARRAY".

Secondly, as your "output" states, you have an array. You need to iterate through your array and insert your records.

A more elegant way to do that would be to generate all your inserts and send them at once to the database server, as the communication between your application server and database server is expensive, that is, it takes time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM