1

我有一个多维数组,想更新/添加一些值,递归。如果可能的话,我想避免构建一个新数组。但我有两个主要问题

  1. 如何“即时”更新值?应该可以使用&-operator.

  2. getDetails()如果函数超出范围,如何获取值以扩展数组。

我的选择是重建一切,但我认为应该有更干净的可能性。

我添加了一些伪代码,希望它不会太奇怪。我感谢您的帮助!

这是小提琴: http: //phpfiddle.org/main/code/m2g-ign

PHP

// build the array 
$myArray = array(
    array(
        "id"   => 1,
        "name" => "A (Level 1)",
        "children" => array(
            array(
                "id"   => 3,
                "name" => "C (Level 2)",
                "children" => array(
                    "id"   => 4,
                    "name" => "D (Level 3)",
                    "children" => null  
                )
            ),              
            array(
                "id"   => 6,
                "name" => "F (Level 2)",
                "children" => array(
                    "id"   => 7,
                    "name" => "G (Level 3)",
                    "children" => null  
                )
            )   
        )
    ),
    array(
        "id"   => 2,
        "name" => "B (Level 1)",
        "children" => array(
            array(
                "id"   => 5,
                "name" => "E (Level 2)",
                "children" => null
            )
        )
    )
);    

// returns detailed data, important: it's out of scope
function getDetails($id) {
    // select dataset from DB
    // ...
    return $details;
}

// loop the array
$RAI = new RecursiveArrayIterator($myArray);
function updateMyArray($iterator) {
    while ($iterator->valid()) {
        if ($iterator->hasChildren()) {
            // recursive
            updateMyArray($iterator->getChildren());
        } else {
            /*
                // 1. set "name" to uppercase
                // Pseudocode:
                $iterator->activeChild()->change(function(&$value) {
                    $value = toUpperCase($value);
                });

                // 2. add Array
                // Pseudocode:
                $id = $iterator->activeChild()->getValue("id");
                $iterator->activeChild()->add("details", getDetails($id));     // getDetails() is out of scope, I guess
            */
        }
        $iterator->next();
    }
}    

echo "<strong>Before:</strong><pre>";
print_r($myArray);
echo "</pre>";

iterator_apply($RAI, 'updateMyArray', array($RAI));
echo "<strong>After:</strong><pre>";
print_r($myArray);
echo "</pre>";
4

0 回答 0