Jump to content

using one foreach loop inside another


fife

Recommended Posts

Im trying to create a folder structure through a script on my site.  At the minute I need to create one folder

 

$topFolders = array('employment');

 

and within that folder set the following array of folders,

 

$subFolders = array('references', 'starter-packs', 'certificates', 'health');

 

I currently have this working fine with the following code...

 

//now make each folder within the branch$topFolders = array('employment'); foreach($topFolders as $folders){$branchTop = mkdir($thisdir . "/uploadedfiles/$branchName/" . $folders, 0777);} //now make the employment system subfolders$subFolders = array('references', 'starter-packs', 'certificates', 'health'); foreach($subFolders as $sub){mkdir($thisdir . "/uploadedfiles/$branchName/employment/" . $sub, 0777);}

 

As you can see this is  very limited.  If for example I need a new top level folder called "residents" and that had the sub folders of "personal, health, notes, signatures" I would have to write a new foreach loop.  Is there a way to make this more dynamic so by adding the new top level folder into the array and its corresponding sub folders the correct set of sub folders is added?  I tried turning it into a function but then suffered the same fate.  I think my array would look as follows

 

employment => 'references', 'starter-packs', 'certificates', 'health',

residents => 'personal', 'health', 'notes', 'signatures'

 

etc

 

 

Link to comment
https://forums.phpfreaks.com/topic/283496-using-one-foreach-loop-inside-another/
Share on other sites

It is better to store the data outside the code and ideally a database would be my choice. However for a simple structure like the one you have an ini file format text file would suit. EG folders.txt containing

[employment]
0='references'
1='starter-packs'
2='certificates'
3='health'

[residents]
0='personal'
1='health'
2='notes'
3='signatures'

To create your array you would then

$folders = parse_ini_file('folders.txt', true);

which would give an array like this:

Folders Array
(
    [employment] => Array
        (
            [0] => references
            [1] => starter-packs
            [2] => certificates
            [3] => health
        )

    [residents] => Array
        (
            [0] => personal
            [1] => health
            [2] => notes
            [3] => signatures
        )

)

To process this array

foreach ($folders as $folder => $subfolders) {
    // create $folder folder
    foreach ($subfolders as $sub) {
        // create subfolder $folder/$sub
    }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.