NYCPHP Meetup

NYPHP.org

[nycphp-talk] next() for multidimensional arrays?

Che Hodgins chehodgins at gmail.com
Thu May 3 02:32:21 EDT 2007


Hi David, see below.

On 5/2/07, David Krings <ramons at gmx.net> wrote:
> Hi!
>
> Is there anything available like next() that will work on
> multidimensional arrays?
> I want to get a flat list of key and value of the current element of a
> multidimensional array. I played around with next() now for an excessive
> amount of time and it just doesn't seem to think in more than one
> dimension. I also cannot make it to without missing some portions of the
> multidimensional array.
>
> Here is what I really want to do:
> I copied the dirlist function from the php.net man page for scandir. The
> function really works well, but returns a multidimensional array with
> the folder names being the keys for the subarrays, whereas files have a
> numerical key. What I need is a one dimensional array that has this
> structure:
> path_to_folder_as_key => filename1
> path_to_folder_as_key => filename2
> path_to_folder_as_key => filename3
> path_to_folder_as_key => filename4
> ....

Since a folder will often contain more than 1 file, using the folder
path as the array key is not a good idea. The key can only be
associated to one value, so in your example the key
path_to_folder_as_key would have the value filename4 only.

A 2 dimensional array such as:

$the_files['path_to_folder_as_key'][0] = filename1
$the_files['path_to_folder_as_key'][1] = filename2
$the_files['path_to_folder_as_key'][2] = filename3
....

Should do it. If you really want to keep a one dimensional array you
could do the following:

$the_files[0] = 'path_to_folder,filename1';
$the_files[1] = 'path_to_folder,filename2';
...

And then when going through the array:

list($path, $file) = explode(',', $the_files[0]);

Good luck,

Che

>
> I also spent quite some time with all the various array flattening
> routines, but due to my lack of skill I cannot get those to keep the
> keys in place or even combine them to a path. It is nice that something
> like scandir is finally available, but PHP is still not very helpful in
> that arena. Nah, it's not PHP, it's me being stupid. I also attempted
> recursion with a function myself, but that ended up in total chaos and
> desaster.
>
> It would be great if one of you smart people could beat me out of this
> .... again.
>
> Best regards,
>
>         David
> _______________________________________________
> New York PHP Community Talk Mailing List
> http://lists.nyphp.org/mailman/listinfo/talk
>
> NYPHPCon 2006 Presentations Online
> http://www.nyphpcon.com
>
> Show Your Participation in New York PHP
> http://www.nyphp.org/show_participation.php
>


-- 
Che Hodgins
www.chehodgins.com
+1 514 312 3950



More information about the talk mailing list