函数名:RecursiveIteratorIterator::getDepth()
适用版本:PHP 5 >= 5.1.0, PHP 7
函数用途:该函数用于获取当前迭代器的深度级别。
语法:int RecursiveIteratorIterator::getDepth ( void )
参数说明:该函数不接受任何参数。
返回值:返回一个整数,表示当前迭代器的深度级别。
示例:
// 创建一个多维数组
$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'
)
);
// 创建一个递归迭代器
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($fruits));
// 遍历数组并输出每个元素的深度级别
foreach ($iterator as $key => $value) {
echo "Key: $key, Value: $value, Depth: " . $iterator->getDepth() . "\n";
}
输出结果:
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
说明:上述示例中,我们首先创建了一个多维数组 $fruits
。然后,我们使用 RecursiveArrayIterator
类将其转换为一个递归迭代器。接下来,我们使用 RecursiveIteratorIterator
类对递归迭代器进行遍历,并通过 getDepth()
方法获取每个元素的深度级别。最后,我们将每个元素的键、值和深度级别输出到屏幕上。