添加/修改php n级关联数组
$arrResult=array(
0=>array('categoryid'=>112,'catname'=>'apperal','subcategory'=>array(
412=>array('categoryid'=>428,'catname'=>'rainwear','subcategory'=>array(
428=>array('categoryid'=>413,'catname'=>'summer','subcategory'=>array()))))));
print_r($arrResult);
$iterator = new RecursiveArrayIterator($arrResult);
iterator_apply($iterator, 'traverseStructure', array($iterator));
function traverseStructure($iterator) {
$arrAddResult=array('categoryid'=>416,'catname'=>'winter','subcategory'=>array());
while ( $iterator -> valid() ) {
if ( $iterator -> hasChildren() ) {
traverseStructure($iterator -> getChildren());
}
else {
if($iterator -> current() == 413)
{
$arr=&$iterator;
$a='arr';
${$a}['subcategory']=$arrAddResult;
break;
}
}
$iterator -> next();
}
}
预期输出是将“arrAddResult”追加到 $arrResult 中。但由于某种原因,迭代器得到修改,但它没有反映 arrResult 数组中的修改。
我尝试在函数“traverseStructure”中通过 ref 传递数组,但仍然难以获得正确的输出。
我首先尝试迭代器。我必须构造一个 N 级关联数组作为 arrResult 因此选择使用迭代器。
$arrResult=array(
0=>array('categoryid'=>112,'catname'=>'apperal','subcategory'=>array(
412=>array('categoryid'=>428,'catname'=>'rainwear','subcategory'=>array(
428=>array('categoryid'=>413,'catname'=>'summer','subcategory'=>array()))))));
print_r($arrResult);
$iterator = new RecursiveArrayIterator($arrResult);
iterator_apply($iterator, 'traverseStructure', array($iterator));
function traverseStructure($iterator) {
$arrAddResult=array('categoryid'=>416,'catname'=>'winter','subcategory'=>array());
while ( $iterator -> valid() ) {
if ( $iterator -> hasChildren() ) {
traverseStructure($iterator -> getChildren());
}
else {
if($iterator -> current() == 413)
{
$arr=&$iterator;
$a='arr';
${$a}['subcategory']=$arrAddResult;
break;
}
}
$iterator -> next();
}
}
the expected output is to append the 'arrAddResult' appenedn in $arrResult. But with some reason the iterator get modify but it doesn't reflect the modification in arrResult array.
I tried passing the array by ref in function 'traverseStructure' but still struggling to get the correct output.
I am trying iterator first. I have to constructor a N-Level associative array as arrResult hence opt to use the iterator.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
下面是一个使用一个数组执行此操作的方法的示例。
这在大型阵列上可能效率低下。我建议创建一个类来缓存 $who 和 $what,这样它就不会被复制到遍历的所有级别。其余的应该是相同的。
Here's an example on a way of doing this with one array.
This might be inefficient on large arrays. I'd recommend making a class that caches the $who and $what so it doesn't get copied to all the levels of the traversal. The rest should be identical.