[pmwiki-devel] php multi-dimensional array construction problem
Peter Bowers
pbowers at pobox.com
Thu Feb 5 09:10:54 CST 2009
I'm giving myself a headache trying to visualize it, but I'm pretty sure
there's a recursive solution in there someplace...
SOMETHING like this...
function dimadd($flatarray, $val)
{
$x = array_shift($flatarray);
if (empty($flatarray))
$m[$x] = $val;
else
$m[$x] = dimadd($flatarray);
return($m);
}
Having proposed that possible solution, it's obvious that it would not be
kind to future maintainers so maybe best left in the theoretical box... :-)
An eval would make it very easy, but perhaps for security purposes you'd
rather avoid that:
$x = '$multidim';
while ($a = array_shift($flatarray))
$x .= "[$a]";
$x .= " = '$val'";
eval($x);
I can't think of any other way to do it right now. Maybe something with
pointers/references (whatever they're called in php) where you build it up
from left-to-right and create a reference to that one for each step along
the way...? Again, in the highly theoretical and totally untested camp:
$multidim = array();
$ref = &$multidim;
while ($a = array_shift($flatarray)) {
$ref[$a] = array();
$ref = &$ref;
}
Note that I always get my pop/push and shift/unshift mixed up so I may be
going from the wrong end on all these solutions.
Hope something here will help at least to get some ideas rolling.
-Peter
On Thu, Feb 5, 2009 at 3:48 PM, Hans <design5 at softflow.co.uk> wrote:
> Thursday, February 5, 2009, 2:28:34 PM, Daniel wrote:
>
> > $string = "k1:k2:k3:...:kn";
> > $array = explode(":", $string);
>
> > //Contents of $array is now:
> > // Array
> > // {
> // [0] =>> k1
> // [1] =>> k2
> // [2] =>> k3
> > // ...
> // [n-1] =>> kn
> > // }
>
> > Avast!
>
> I got so far, but the "avast!" defeats me. Perhaps I am thick ;-)
>
> How do I construct out of that nice flat array this array-element:
>
> n deep array $arr
> element needed
> $val = arr[$k[0]][$k[1]][$k[2]]....[$k[$n]];
> or element set
> $arr[$k[0]][$k[1]][$k[2]]....[$k[n]] = $val;
>
> How can the ... be constructed, with n being a variable integer?
>
> Thanks,
> Hans
>
>
> _______________________________________________
> pmwiki-devel mailing list
> pmwiki-devel at pmichaud.com
> http://www.pmichaud.com/mailman/listinfo/pmwiki-devel
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.pmichaud.com/pipermail/pmwiki-devel/attachments/20090205/cc9ed03d/attachment-0001.html
More information about the pmwiki-devel
mailing list