函數(shù)名:RecursiveIteratorIterator::getDepth()
適用版本:PHP 5 >= 5.1.0, PHP 7
函數(shù)用途:該函數(shù)用于獲取當(dāng)前迭代器的深度級(jí)別。
語法:int RecursiveIteratorIterator::getDepth ( void )
參數(shù)說明:該函數(shù)不接受任何參數(shù)。
返回值:返回一個(gè)整數(shù),表示當(dāng)前迭代器的深度級(jí)別。
示例:
// 創(chuàng)建一個(gè)多維數(shù)組
$fruits = array(
'apple' => array(
'color' => 'red',
'taste' => 'sweet',
'origin' => 'USA'
),
'banana' => array(
'color' => 'yellow',
'taste' => 'sweet',
'origin' => 'South America'
),
'orange' => array(
'color' => 'orange',
'taste' => 'sour',
'origin' => 'China'
)
);
// 創(chuàng)建一個(gè)遞歸迭代器
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($fruits));
// 遍歷數(shù)組并輸出每個(gè)元素的深度級(jí)別
foreach ($iterator as $key => $value) {
echo "Key: $key, Value: $value, Depth: " . $iterator->getDepth() . "\n";
}
輸出結(jié)果:
Key: color, Value: red, Depth: 1
Key: taste, Value: sweet, Depth: 1
Key: origin, Value: USA, Depth: 1
Key: apple, Value: Array, Depth: 0
Key: color, Value: yellow, Depth: 1
Key: taste, Value: sweet, Depth: 1
Key: origin, Value: South America, Depth: 1
Key: banana, Value: Array, Depth: 0
Key: color, Value: orange, Depth: 1
Key: taste, Value: sour, Depth: 1
Key: origin, Value: China, Depth: 1
Key: orange, Value: Array, Depth: 0
說明:上述示例中,我們首先創(chuàng)建了一個(gè)多維數(shù)組 $fruits
。然后,我們使用 RecursiveArrayIterator
類將其轉(zhuǎn)換為一個(gè)遞歸迭代器。接下來,我們使用 RecursiveIteratorIterator
類對(duì)遞歸迭代器進(jìn)行遍歷,并通過 getDepth()
方法獲取每個(gè)元素的深度級(jí)別。最后,我們將每個(gè)元素的鍵、值和深度級(jí)別輸出到屏幕上。