16

我怀疑我在这里做了一些愚蠢的事情,但我对 SPL 的一个简单问题感到困惑:

如何使用RecursiveArrayIterator / RecursiveIteratorIterator修改数组的内容(本例中的值) ?

使用以下测试代码,我可以使用getInnerIterator()offsetSet()更改循环内的值,并在循环内转储修改后的数组。

但是当我离开循环并从迭代器中转储数组时,它又回到了原始值。发生了什么?

$aNestedArray = array();
$aNestedArray[101] = range(100, 1000, 100);
$aNestedArray[201] = range(300, 25, -25);
$aNestedArray[301] = range(500, 0, -50);

$cArray = new ArrayObject($aNestedArray);
$cRecursiveIter = new RecursiveIteratorIterator(new RecursiveArrayIterator($cArray), RecursiveIteratorIterator::LEAVES_ONLY);

// Zero any array elements under 200  
while ($cRecursiveIter->valid())
{
    if ($cRecursiveIter->current() < 200)
    {
        $cInnerIter = $cRecursiveIter->getInnerIterator();
        // $cInnerIter is a RecursiveArrayIterator
        $cInnerIter->offsetSet($cInnerIter->key(), 0);
    }

    // This returns the modified array as expected, with elements progressively being zeroed
    print_r($cRecursiveIter->getArrayCopy());

    $cRecursiveIter->next();
}

$aNestedArray = $cRecursiveIter->getArrayCopy();

// But this returns the original array.  Eh??
print_r($aNestedArray);
4

7 回答 7

5

看起来普通数组中的值是不可修改的,因为它们不能通过引用传递给ArrayIterator(从此类RecursiveArrayIterator继承其方法,请参阅SPL 参考)的构造函数。所以所有调用都在数组的副本上工作。offset*()offsetSet()

我猜他们选择避免​​引用调用是因为它在面向对象的环境中没有多大意义(即,当传递ArrayObject应该是默认情况的实例时)。

更多代码来说明这一点:

$a = array();

// Values inside of ArrayObject instances will be changed correctly, values
// inside of plain arrays won't
$a[] = array(new ArrayObject(range(100, 200, 100)),
             new ArrayObject(range(200, 100, -100)),
             range(100, 200, 100));
$a[] = new ArrayObject(range(225, 75, -75));

// The array has to be
//     - converted to an ArrayObject or
//     - returned via $it->getArrayCopy()
// in order for this field to get handled properly
$a[] = 199;

// These values won't be modified in any case
$a[] = range(100, 200, 50);

// Comment this line for testing
$a = new ArrayObject($a);

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));

foreach ($it as $k => $v) {
    // getDepth() returns the current iterator nesting level
    echo $it->getDepth() . ': ' . $it->current();

    if ($v < 200) {
        echo "\ttrue";

        // This line is equal to:
        //     $it->getSubIterator($it->getDepth())->offsetSet($k, 0);
        $it->getInnerIterator()->offsetSet($k, 0);
    }

    echo ($it->current() == 0) ? "\tchanged" : '';
    echo "\n";
}

// In this context, there's no real point in using getArrayCopy() as it only
// copies the topmost nesting level. It should be more obvious to work with $a
// itself
print_r($a);
//print_r($it->getArrayCopy());
于 2009-08-11T07:45:13.817 回答
5

您需要getSubIterator在当前深度调用,在该深度使用offsetSet,并对返回树的所有深度执行相同操作。

这对于在数组或数组中的值上进行无限级别的数组合并和替换非常有用。不幸的是,array_walk_recursive在这种情况下将不起作用,因为该函数仅访问叶节点..因此将永远不会访问下面 $array 中的“replace_this_array”键。

例如,要替换深度未知级别的数组中的所有值,但仅替换那些包含某个键的值,您可以执行以下操作:

$array = [
    'test' => 'value',
    'level_one' => [
        'level_two' => [
            'level_three' => [
                'replace_this_array' => [
                    'special_key' => 'replacement_value',
                    'key_one' => 'testing',
                    'key_two' => 'value',
                    'four' => 'another value'
                ]
            ],
            'ordinary_key' => 'value'
        ]
    ]
];

$arrayIterator = new \RecursiveArrayIterator($array);
$completeIterator = new \RecursiveIteratorIterator($arrayIterator, \RecursiveIteratorIterator::SELF_FIRST);

foreach ($completeIterator as $key => $value) {
    if (is_array($value) && array_key_exists('special_key', $value)) {
        // Here we replace ALL keys with the same value from 'special_key'
        $replaced = array_fill(0, count($value), $value['special_key']);
        $value = array_combine(array_keys($value), $replaced);
        // Add a new key?
        $value['new_key'] = 'new value';

        // Get the current depth and traverse back up the tree, saving the modifications
        $currentDepth = $completeIterator->getDepth();
        for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--) {
            // Get the current level iterator
            $subIterator = $completeIterator->getSubIterator($subDepth); 
            // If we are on the level we want to change, use the replacements ($value) other wise set the key to the parent iterators value
            $subIterator->offsetSet($subIterator->key(), ($subDepth === $currentDepth ? $value : $completeIterator->getSubIterator(($subDepth+1))->getArrayCopy()));
        }
    }
}
return $completeIterator->getArrayCopy();
// return:
$array = [
    'test' => 'value',
    'level_one' => [
        'level_two' => [
            'level_three' => [
                'replace_this_array' => [
                    'special_key' => 'replacement_value',
                    'key_one' => 'replacement_value',
                    'key_two' => 'replacement_value',
                    'four' => 'replacement_value',
                    'new_key' => 'new value'
                ]
            ],
            'ordinary_key' => 'value'
        ]
    ]
];
于 2016-11-08T10:01:22.777 回答
4

不使用 Iterator 类(这似乎是在复制数据RecursiveArrayIterator::beginChildren()而不是通过引用传递。)

您可以使用以下内容来实现您想要的

function drop_200(&$v) { if($v < 200) { $v = 0; } }

$aNestedArray = array();
$aNestedArray[101] = range(100, 1000, 100);
$aNestedArray[201] = range(300, 25, -25);
$aNestedArray[301] = range(500, 0, -50);

array_walk_recursive ($aNestedArray, 'drop_200');

print_r($aNestedArray);

或使用create_function()而不是创建 drop_200 函数,但您的里程可能会因 create_function 和内存使用情况而异。

于 2010-01-13T18:40:25.053 回答
2

看起来 getInnerIterator 创建了子迭代器的副本。

也许有不同的方法?(敬请关注..)


更新:在对它进行了一段时间的修改并引入了 3 名其他工程师之后,看起来 PHP 并没有为您提供更改 subIterator 值的方法。

您始终可以使用旧的备用:

<?php  
// Easy to read, if you don't mind references (and runs 3x slower in my tests) 
foreach($aNestedArray as &$subArray) {
    foreach($subArray as &$val) {
       if ($val < 200) {
            $val = 0;
        }
    }
}
?>

或者

<?php 
// Harder to read, but avoids references and is faster.
$outherKeys = array_keys($aNestedArray);
foreach($outherKeys as $outerKey) {
    $innerKeys = array_keys($aNestedArray[$outerKey]);
    foreach($innerKeys as $innerKey) {
        if ($aNestedArray[$outerKey][$innerKey] < 200) {
            $aNestedArray[$outerKey][$innerKey] = 0;
        }
    }
}
?>
于 2009-08-04T17:41:59.613 回答
2

首先将数组转换为对象,它按预期工作..

    $array = [
        'one' => 'One',
        'two' => 'Two',
        'three' => [
            'four' => 'Four',
            'five' => [
                'six' => 'Six',
                'seven' => 'Seven'
            ]
        ]
    ];

    // Convert to object (using whatever method you want)
    $array = json_decode(json_encode($array));

    $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
    foreach($iterator as $key => $value) {
        $iterator->getInnerIterator()->offsetSet($key, strtoupper($value));
    }

    var_dump($iterator->getArrayCopy());
于 2017-04-03T18:44:49.297 回答
0

是否可以归结为按引用传递与按值传递?

例如尝试更改:

$cArray = new ArrayObject($aNestedArray);

至:

$cArray = new ArrayObject(&$aNestedArray);
于 2009-08-04T20:47:11.267 回答
0

我知道这并不能直接回答您的问题,但是在迭代对象时修改迭代对象并不是一个好习惯。

于 2009-08-04T17:54:45.373 回答