2

Solution Found: Dynamic array keys


I have a multi dimensional dynamic array, the format of which varies. for example.

$data = array('blah1'=>array('blah2'=>array('hello'=>'world')));

I then have a dynamic pathway as a string.

$pathway = 'blah1/blah2/hellow';

The pathway is broken up into it's component parts, for simplicities' sake:

$pathway_parts = explode('/', $pathway);

My problem arises from wanting to set the value of 'hello'. The way I currently do it is via eval, but I want to illiminate this evil partly because of the php Suhosin hardening breaking the app, but also because I don't believe this is the best way.

eval('$data["'.implode('"]["', $pathway_parts).'"] = $value;');

$data must always return the full array because further down the array it is serialised and stored. What would the best way to transverse the array to set the value without the use of eval?

Community
  • 1
  • 1
buggedcom
  • 1,537
  • 2
  • 18
  • 34
  • I can't think of a good way to do this without eval, given the multidimensional array is dynamic and might have different amount of depth levels each call. Are you sure this is the best implementation for your problem? – Dvir Oct 07 '11 at 14:44
  • 1
    I am thinking drill down to the lowest level and then get a pointer to reference that value and change it I am not to familiar with pointers in php and I am kinda drawing a blank to drill down... But I think it would work.. – Laurence Burke Oct 07 '11 at 14:47
  • @LaurenceBurke - exactly. the solution i found (see top of post) does exactly that. – buggedcom Oct 07 '11 at 14:48
  • YAY for me didnt even realize I was on the right track.... I R SMRT – Laurence Burke Oct 07 '11 at 14:50

2 Answers2

2

You can do this using references to gradually work your way to referencing that value.

$data = array('blah1'=>array('blah2'=>array('hello'=>'world')));
$pathway = 'blah1/blah2/hello';
$pathway_parts = explode('/', $pathway);
$ref = &$data;

foreach ($pathway_parts as $part)
{
   // Possibly check if $ref[$part] is set before doing this.
   $ref = &$ref[$part];
}

$ref = 'value';

var_export($data);
Paul
  • 6,572
  • 2
  • 39
  • 51
0

this doesn't sound like the best structure, but something like this might work:

//$data = array('blah1'=>array('blah2'=>array('hello'=>'world')));
$pathway = 'blah1/blah2/hellow';
$pathway_parts = explode('/', $pathway);
$value = 'some value';

$data = $value;
while($path = array_pop($pathway_parts)){
    $data = array($path=>$data);
}
echo '<pre>'.print_r($data,true).'</pre>';

Other than that, you might be able to build a json string and use json_decode on it. json_decode doesn't execute code.

Jonathan Kuhn
  • 15,279
  • 3
  • 32
  • 43