Jump to content

[SOLVED] Create multidimensional array dynamically


baennaeck

Recommended Posts

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

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>';
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.