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

Link to comment
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.