函數(shù)名稱:RecursiveIteratorIterator::endIteration()
函數(shù)描述:該函數(shù)用于在迭代器的每次迭代結束時調(diào)用,以便在迭代結束時執(zhí)行一些特定的操作。
適用版本:PHP 5, PHP 7
語法:void RecursiveIteratorIterator::endIteration ( void )
示例:
// 創(chuàng)建一個多維數(shù)組
$array = array(
'fruit' => array(
'apple' => array('green', 'red'),
'banana' => array('yellow'),
),
'color' => array(
'blue',
'red',
'green',
),
);
// 創(chuàng)建一個遞歸迭代器
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array),
RecursiveIteratorIterator::SELF_FIRST
);
// 定義一個回調(diào)函數(shù),在迭代結束時輸出當前迭代的鍵和值
function endIterationCallback() {
global $iterator;
$key = $iterator->key();
$value = $iterator->current();
echo "End of iteration: Key = $key, Value = $value\n";
}
// 設置回調(diào)函數(shù)
$iterator->endIterationCallback('endIterationCallback');
// 開始迭代
foreach ($iterator as $key => $value) {
echo "Key: $key, Value: $value\n";
}
輸出結果:
Key: fruit, Value: Array
Key: apple, Value: Array
Key: 0, Value: green
End of iteration: Key = 0, Value = green
Key: 1, Value: red
End of iteration: Key = 1, Value = red
Key: banana, Value: Array
Key: 0, Value: yellow
End of iteration: Key = 0, Value = yellow
Key: color, Value: Array
Key: 0, Value: blue
End of iteration: Key = 0, Value = blue
Key: 1, Value: red
End of iteration: Key = 1, Value = red
Key: 2, Value: green
End of iteration: Key = 2, Value = green
在上面的示例中,我們創(chuàng)建了一個多維數(shù)組并使用遞歸迭代器進行迭代。在每次迭代結束時,回調(diào)函數(shù)endIterationCallback()
被調(diào)用,并輸出當前迭代的鍵和值。通過使用endIterationCallback()
函數(shù),我們可以在每次迭代結束時執(zhí)行特定的操作。