添加/修改php n级关联数组

时间:2011-04-15 03:51:55

标签: php associative-array

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

预期输出是在$ arrResult中附加'arrAddResult'appenedn。但由于某种原因,迭代器得到修改,但它没有反映arrResult数组中的修改。

我尝试在函数'traverseStructure'中通过ref传递数组,但仍然在努力获得正确的输出。

我首先尝试迭代器。我必须构造一个N级关联数组作为arrResult因此选择使用迭代器。

1 个答案:

答案 0 :(得分:0)

以下是一个使用一个数组进行此操作的示例。

<?php
$arrResult=array(
    1=>array('categoryid'=>112,'catname'=>'apperal','subcategory'=>array()),
    0=>array('categoryid'=>112,'catname'=>'apperal','subcategory'=>array(
        1=>array('categoryid'=>112,'catname'=>'rainwear','subcategory'=>array(
            1=>array('categoryid'=>112,'catname'=>'apperal','subcategory'=>array()),
            428=>array('categoryid'=>413,'catname'=>'summer','subcategory'=>array()))
            ),
        412=>array('categoryid'=>428,'catname'=>'rainwear','subcategory'=>array(
            1=>array('categoryid'=>112,'catname'=>'apperal','subcategory'=>array()),
            428=>array('categoryid'=>413,'catname'=>'summer','subcategory'=>array()))
            )
        )
    )
);

function append(&$ar,$who,$what){
    // just a simple check, you can remove it
    if(!is_array($ar))return false;
    // loop through all keys
    foreach($ar as $k=>$v){
        // found node, i'm assuming you don't have the node multiple times
            // if you want this to go forever, remove the returns and the if on the add()
        if($v['categoryid']==$who){
            $ar[$k]['subcategory'][]=$what;
            return true;
        }
        // recursion !
        if(add($ar[$k]['subcategory'],$who,$what))return true;// if found stop
    }
    // key not found here in this node or subnodes
    return false;
}
append($arrResult,413,array('categoryid'=>416,'catname'=>'winter','subcategory'=>array()));
echo'<pre>';
var_dump($arrResult);

这在大型阵列上可能效率低下。我建议创建一个缓存$ who和$的类,以便它不会被复制到遍历的所有级别。其余的应该是相同的。