PHP:使用单独数组中定义的路径设置多维关联数组元素的值
好的,我有一个包含以下元素的数组:
$array['a']['b'][0]['c'];
$array['a']['b'][1]['c'];
$array['a']['d'][0]['c']['c'];
$array['b']['c'];
然后在一个单独的数组中,我定义了这些值的路径:
$structure[0] = array('a','b','#','c');
$structure[1] = array('a','d','#','c','c');
$structure[2] = array('b','c');
最后,我有一个包含这些值的数组:
$values[0] = array('value0-0','value0-1');
$values[1] = array('value1-0');
$values[2] = array('value2-0');
我试图找到一个简单的函数/循环,它将能够将 $values 中的值应用到 $struct 中定义的 $array 的数组路径。
最终结果将是:
$array['a']['b'][0]['c']='value0-0';
$array['a']['b'][1]['c']='value0-1';
$array['a']['d'][0]['c']['c']='value1-0';
$array['b']['c']='value2-0';
在 $values[0] 或 $values[1] 的情况下,它将能够循环遍历每个值,并将与“#”匹配的 $struct 元素替换为该特定 $value 的迭代编号。
这只是一个简单的情况,就是认真编写一个冗长的递归函数,还是有一个智能构造或 php 函数可以提供更优雅的解决方案?
解决方案:
感谢 Mario,我最终的解决方案是:
foreach ($struct as $i=>$keys)
foreach ($values[$i] as $val) {
$r = & $array;
foreach ($keys as $key) {
if ($key == "#") { $key = $i; }
$r = & $r[$key]; // move pointer to subarray
}
$r = $val;
}
}
Ok so I have an array that holds the following elements:
$array['a']['b'][0]['c'];
$array['a']['b'][1]['c'];
$array['a']['d'][0]['c']['c'];
$array['b']['c'];
Then in a separate array, I have defined the path to these values:
$structure[0] = array('a','b','#','c');
$structure[1] = array('a','d','#','c','c');
$structure[2] = array('b','c');
Finally, I have an array holding the values:
$values[0] = array('value0-0','value0-1');
$values[1] = array('value1-0');
$values[2] = array('value2-0');
I'm trying to find a simple function/loop that will be able to apply the values in $values to the array path of $array that is defined in $structure.
The end result would be:
$array['a']['b'][0]['c']='value0-0';
$array['a']['b'][1]['c']='value0-1';
$array['a']['d'][0]['c']['c']='value1-0';
$array['b']['c']='value2-0';
In the case of $values[0] or $values[1], it would be able to loop through each value and substitute the $structure element matching '#' with the iteration number for that particular $value.
Is this simply a case of knuckling down and writing a drawn out recursive function, or is there a smart construct or php function that could provide a more elegant solution?
SOLUTION:
Thanks to Mario, my eventual solution is:
foreach ($struct as $i=>$keys)
foreach ($values[$i] as $val) {
$r = & $array;
foreach ($keys as $key) {
if ($key == "#") { $key = $i; }
$r = & $r[$key]; // move pointer to subarray
}
$r = $val;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须使用引用来遍历目标数组:
You will have to work with references to traverse the target array: