baennaeck Posted April 17, 2007 Share Posted April 17, 2007 Hi! I'm already trying for some days to create an array dynamically. I have the following situation: I have an array of strings. $data["base:foo:bar"] = "test1"; $data["base:foo2:bar"] = "test2"; $data["base:foo2:bar2"] = "test3"; $data["base:foo:bar2"] = "test4"; This array should be converted in a multidimensional array. The keys for this array are the above keys separated by colons. The dimension of the array varies form situation to situation. So the result should be: array(1) { ["base"]=> array(2) { ["foo"]=> array(2) { ["bar"]=> string("test1") ["bar2"]=> string("test4") } ["foo2"]=> array(2) { ["bar"]=> string("test2") ["bar2"]=> string("test3") } } } The following skeleton iterates over the two arrays to get the keys and the values. But I have no idea how to create the array. foreach ($data as $pKey => $pValue){ $exp = explode(":", $pKey); foreach ( $exp as $val ) { // build array } } I tried a lot but without any success. I would be very happy if someone could help me. Best wishes, baennaeck Link to comment https://forums.phpfreaks.com/topic/47468-solved-create-multidimensional-array-dynamically/ Share on other sites More sharing options...
sasa Posted April 17, 2007 Share Posted April 17, 2007 try <?php $data["base:foo:bar"] = "test1"; $data["base:foo2:bar"] = "test2"; $data["base:foo2:bar2"] = "test3"; $data["base:foo:bar2"] = "test4"; foreach ($data as $pKey => $pValue){ $exp = explode(":", $pKey); $x = "\$out['"; //foreach ( $exp as $val ) { // build array //} $x .= implode("']['",$exp)."'] = '$pValue';"; eval($x); } echo '<pre>'; print_r($out); echo '</pre>'; ?> Link to comment https://forums.phpfreaks.com/topic/47468-solved-create-multidimensional-array-dynamically/#findComment-231661 Share on other sites More sharing options...
baennaeck Posted April 18, 2007 Author Share Posted April 18, 2007 Perfect! Thanks a lot! Link to comment https://forums.phpfreaks.com/topic/47468-solved-create-multidimensional-array-dynamically/#findComment-231744 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.