I have a standard array with key-value pairs - and I want to use keys to convert it to a multidimensional array. The difficulty seems to be that I need to recursively quote an unknown number of new keys and turn them into a multidimensional array. In short, I want this:
$val[alfa.xray.uno] = "Some value"; => $val['alfa']['xray']['uno'] = "Some value";
Example: (The code does not work and should also handle N measurements, but you get the idea ..)
$arr['alfa.xray.uno'] = "Alfa X-Ray Uno"; $arr['alfa.yaho.duo'] = "Alfa Yaho Duo"; $arr['beta.xray.uno'] = "Beta X-Ray Uno"; $arr['beta.xray.duo'] = "Beta X-Ray Duo"; $arr['just-me'] = "Root-level item"; print_r( array_flat_to_multidimensional($arr) ); function array_flat_to_multidimensional($arr) { foreach($arr as $key=>$val) { $key = explode(".",$key); for($i=0; $i<count($key); $i++) { if($i==0) { $out[$key[$i]] = $val; } else if($i==1) { $out[$key[$i-1]][$key[$i]] = $val; } else if($i==2) { $out[$key[$i-2]][$key[$i-1]][$key[$i]] = $val; } else if($i==3) { $out[$key[$i-3]][$key[$i-2]][$key[$i-1]][$key[$i]] = $val; } } } return $out; }
Perhaps RecursiveArrayIterator will do the trick?
source share