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 に答える
0

それは、参照による受け渡しと値による受け渡しに帰着することができますか?

たとえば、次のように変更してみてください。

$cArray = new ArrayObject($aNestedArray);

に:

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

これがあなたの質問に直接答えないことは知っていますが、反復中にオブジェクトを変更することはお勧めできません。

于 2009-08-04T17:54:45.373 に答える