Re: Appending into associative arrays

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Zoltán Németh wrote:
> 2007. 04. 16, hétfő keltezéssel 10.50-kor Zoltán Németh ezt írta:
>> 2007. 04. 16, hétfő keltezéssel 10.40-kor Otto Wyss ezt írta:
>>> Zoltán Németh wrote:
>>>> what do you mean by doesn't work? what error is thrown if any? what
>>>> result do you get instead of the expected?
>>>> at first glance I cannot see anything wrong with your function...
>>>>
>>> It simply doesn't add any sub folder to $dirs. Could it be that the 
>>> function doesn't return the $dirs parameter?
>> yes at second look I see the problem. you should do it this way:
>>
>> function recurseDir ($base, $accending = true, $dirs = array()) {
>>      $handle = opendir ($base);
>>      while ($dir = readdir($handle)) {
>>        if (($dir != '..') and ($dir != '.')) {
>>          $d = $base.'/'.$dir;
>>          if (is_dir ($d)) {
>>            $dirs[$d] = filemtime($d);
>>            $dirs = recurseDir ($d, true, $dirs);
>>          }
>>        }
>>      }
>>      closedir ($handle);
>>      asort ($dirs);
>>      return $accending? $dirs: array_reverse ($dirs);
>>    }
>>
>> and then you can call array_keys on the result of the whole recursion
>> like:
>> $dirnames = array_keys($base, $accending);
> 
> ehh typo in the above line, sorry
> 
> $dirnames = array_keys(recurseDir($base, $accending));

It would be much cleaner to not pass $dirs into the function and
use array_merge() on the returned array instead, additionally
having to call array_keys() on the call to recurseDir() seems rather
lame (too much of wtf factor imho).

function recurseDir ($base, $ascending = true, $self_called = false) {
     $handle = opendir($base);
     $dirs   = array();
     while ($dir = readdir($handle)) {
       if (($dir != "..") and ($dir != ".")) {
         $d = $base."/".$dir;
         if (is_dir ($d)) {
           $dirs[$d] = filemtime($d);
           $dirs = array_merge($dirs, recurseDir($d, $ascending, true));
         }
       }
     }

     closedir ($handle);

     if ($self_called) {
	return $dirs;
     } else {
	asort ($dirs);
        return array_keys($ascending ? $dirs : array_reverse($dirs));
     }
}


not exactly pretty, what with the use of $self_called - but at least it keeps
all the crap inside the function.

> 
> greets
> Zoltán Németh
> 
>> greets
>> Zoltán Németh
>>
>>> O. Wyss
>>>
> 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux