Jump to content

help building call to multidemensional array


mdillon

Recommended Posts

This is driving me a bit crazy. I know I'm not doing this right.

I have a multidemensional array, such that each array in it may have some values that are a string and some that are an array. I need to take a string and turn it into a variable that calls a value from the array.

Example:
<?php
//I have this string:
$string = "a.b.c.d.e";

//It is really a . delimited shorthand note to find an array value:
$a['b']['c']['d']['e']
//So I want to turn the string into that, and call the value.

//say the actual value in there is:
$a['b']['c']['d']['e'] = "foo";

//I tried parsing the string by its delimiter:
$part = explode(".", $string);
$build = $part[0];
for($i = 1; $i < count($part); $i++){
$build .=  "['$part[$i]']";
}
//So now $build is the string "a['b']['c']['d']['e']"
//now how do I convince php to turn that into a real call to the array's value?

//these do not work:
$result = $$build;
$result = ${$build};
?>
They just make the value of the variable named "result" be the variable named
"a['b']['c']['d']['e']" which is not actually what I want. I need the value of "result" to be the e index of the d index of the c index of the b index of the array that is the value of the variable named "a"... I think.

Note that I cannot just do this:
<?php
$result = ${$part[0]}[$part[1]][$part[2]][$part[3]][$part[4]]";
?>
Even though that works, the point is that the string I am given might ask for any level of the multidemensional array.
eg
$string = "a.b.e";
where
$a['b]['e'] = "bar";

Thus I need something to parse and assemble the string by however many places it happens to have. But I dunno how to convince PHP what I want to do with the result.

Thanks for any ideas.
try
[code]
<?php
/**
* test array
*/
$a['b']['c']['d']['e']  = 42;

$string = 'a.b.c.d.e';
$part = explode('.', $string);
$build = '$'.$part[0];
for($i = 1; $i < count($part); $i++){
  $build .=  "['$part[$i]']";
}


eval ("\$res = $build;");
echo $res;
?>
[/code]

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.