[thelist] writing array contents to file

Jeffrey Barke jeffrey.barke at themechanism.com
Sun Jun 22 13:26:53 CDT 2008


Quoting Aaron Vegh <aaronvegh at gmail.com>:

> Hi there,
> I have an array that contains directory names, file names and file
> contents. I need to write a function that iterates through the array,
> and for each array key that doesn't contain a "." write a directory
> instead of a file. Here's a simplified array that's structured
> similarly to the target array:

Aaron,

I think looping through the array and creating the directories isn't  
too hard, but I'm having difficultly keeping the directory structure  
intact. The following code works for your sample array, but it has  
serious limitations:

1. If you reverse the order of the 'library' array, all of the  
directories get created, but the structure is broken.

2. If you add a third level of subdirectories, the structure gets broken.

Hopefully this helps a little bit,
Jeffrey

<?php

$dirRoot = $_SERVER['DOCUMENT_ROOT'] . '/';
$curPath = '';
$depth = 0;

$array = array(
         'setup' => array (
                 'file1.txt'=>'file1 contents',
                 'file2.txt'=>'file2 contents'
         ),
         'images' => array (
                 'image1.gif'=>'image1contents',
                 'image2.gif'=>'image2contents'
         ),
         'library' => array(
                 'settings_conf' => array (
                         'conf1.txt'=>'conf1 contents',
                         'conf2.txt'=>'conf2 contents'
                 ),
                 'settings_conf1.txt'=>'contents'
         ),
         'config.txt'=>'configuration contents'
);

function arrayToDir($array, $curPath = '') {
         global $dirRoot, $curPath, $depth;
         foreach ($array as $key => $val) {\
                 if (strpos($key, '.') === false) {
                         mkdir($dirRoot . $curPath . $key, 0777);
                 }
                 if (is_array($val)) {
                         if ($depth == 0) {
                                 $curPath = $key . '/';
                                 $depth++;
                         }
                         arrayToDir($val, $curPath);
                 } else {
                         if ($depth > 0) {
                                 $depth--;
                         }
                         if ($depth == 0) {
                                 $curPath = '';
                         }
                 }

         }
}

arrayToDir($array);
echo '<p>Done!</p>';

?>



More information about the thelist mailing list