当路径是动态的时,在多维数组中设置值的最佳方式


PHP, Best way of setting a value in a multi-dimensional array when the pathway is dynamic?

解决方案:动态数组键


我有一个多维动态数组,其格式各不相同。例如,

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

我有一个动态路径作为字符串。

$pathway = 'blah1/blah2/hellow';

为了简单起见,路径被分解成它的组成部分:

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

我的问题来自想要设置'hello'的值。我目前的方法是通过eval,但我想消除这个邪恶,部分原因是php的Suhosin加固破坏了应用程序,但也因为我不相信这是最好的方法。

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

$data必须总是返回完整的数组,因为它在数组的后面被序列化和存储。在不使用eval的情况下横向数组设置值的最佳方法是什么?

您可以使用引用来逐步地引用该值。

$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);

这听起来不是最好的结构,但是像这样的东西可能会起作用:

//$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>';

除此之外,您可以构建一个json字符串并对其使用json_decode。Json_decode不执行代码