Gunter Sammet wrote:
> Hi all:
> I've been trying to create a multidimensional array with n depth in php.
> Tried to use a recursive function passing array references by pointers but
> seems like it's not possible or I still don't understand this subject
> enough. Finally managed to get it going using the eval function. The code
> below converts a seperated string into a multi dimensional array with n
> depth:
>
> e.g. $array['1_20-2_16-7_14'] = 12 will become
> $eval_array[1][20][2][16][7][14] = 12
>
> foreach(array_keys($this->quantity_array) AS $key){
> if($this->quantity_array[$key] > 0){
> $combinations = explode('-', $key);
> $eval_string = '$eval_array';
> foreach(array_keys($combinations) AS $key2){
> $option_key_value = explode('_', $combinations[$key2]);
> $eval_string .=
> '['.$option_key_value[0].']['.$option_key_value[1].']';
> }
> $eval_string .= ' = '.$this->quantity_array[$key].';';
> eval($eval_string);
the following 5 lines were contributed by my 2 yo.
> 1112`11q\| `1@
]1
qA|]
]"A||z\'\'sas
}
> }
something like (I use a simalar technique to
manage 'namespaced' data stored in $_SESSION):
// input
$array = array(
"1_20-2_16-7_14" => 12,
"1_20-1_17-5_12" => 13,
"1_20-0_18-3_11" => 12,
);
// output
$ML = array();
//process
foreach ($array as $keys => $val) {
// grab a ref to the root of the output array
$tmp =& $ML;
// get keys we want to build from - hackish but will do for this example
$keys = explode("_", str_replace("-","_",trim($keys)));
// build from the list of keys
foreach ($keys as $k) {
if (!isset($tmp[$k]))
$tmp[$k] = array();
$tmp =& $tmp[$k];
}
// stick the value into the deepest array.
$tmp = $val;
}
// display output
var_dump($ML);
>
> Using eval() for it seems a bit expensive to me. So I've been wondering if
indeed - if your using eval() then there is pretty much always a better way;
unless there isn't and then you probably don't need any help from this list :-)
> there is an easier way?
dunno, but there is usually a highway. ;->
> TIA
>
> Gunter
>
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php