1

Here is my dilemma and thank you in advance!

I am trying to create a variable variable or something of the sort for a dynamic associative array and having a hell of a time figuring out how to do this. I am creating a file explorer so I am using the directories as the keys in the array.

Example:
I need to get this so I can assign it values

$dir_list['root']['folder1']['folder2'] = value;

so I was thinking of doing something along these lines...

if ( $handle2 = @opendir( $theDir.'/'.$file ))
{
    $tmp_dir_url = explode($theDir);
    for ( $k = 1; $k < sizeof ( $tmp_dir_url ); $k++ )
    {
        $dir_list [ $dir_array [ sizeof ( $dir_array ) - 1 ] ][$tmp_dir_url[$k]]
    }

this is where I get stuck, I need to dynamically append a new dimension to the array durring each iteration through the for loop...but i have NO CLUE how

3 Answers 3

2

I would use a recursive approach like this:

function read_dir_recursive( $dir ) {
    $results = array( 'subdirs' => array(), 'files' => array() );
    foreach( scandir( $dir ) as $item ) {
        // skip . & ..
        if ( preg_match( '/^\.\.?$/', $item ) )
            continue;
        $full = "$dir/$item";
        if ( is_dir( $full ) )
            $results['subdirs'][$item] = scan_dir_recursive( $full );
        else
            $results['files'][] = $item;
    }
}

The code is untested as I have no PHP here to try it out.

Cheers,
haggi

0
0

You can freely put an array into array cell, effectively adding 1 dimension for necessary directories only.

I.e.

$a['x'] = 'text';
$a['y'] = new array('q', 'w');

print($a['x']);
print($a['y']['q']);
0

How about this? This will stack array values into multiple dimensions.

$keys = array(
'year',
'make',
'model',
'submodel',
);

$array = array(); print_r(array_concatenate($array, $keys)); function array_concatenate($array, $keys){ if(count($keys) === 0){ return $array; } $key = array_shift($keys); $array[$key] = array(); $array[$key] = array_concatenate($array[$key], $keys); return $array; }

In my case, I knew what i wanted $keys to contain. I used it to take the place of:

if(isset($array[$key0]) && isset($array[$key0][$key1] && isset($array[$key0][$key1][$key2])){ // do this }

Cheers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.