下面是模式密鑰1個值A鍵3值B鍵4值d,E,F的答案,G鍵5值C
$tree = array (
1 => array (
2 => "A",
3 => "B",
4 => array (
6 => "D",
7 => array (
8 => "E",
9 => array (
10 => "F",
11 => "G"
)
)
),
5 => "C"
)
);
// Loop through $tree array
// Since you are assigning array to index 1,
// Use $tree[1] instead of just $tree
foreach($tree[1] as $key => $value)
{
// Pring key
echo "Key {$key}: ";
// Check key value type is array or not
if (gettype($value) == 'array')
{
// if it's array data type call recursive function
print_array($value);
}
else
{
// just pring value
echo "{$value}, ";
}
echo "\n";
}
// Recursive function
// Takes array as parameter
function print_array(array $array)
{
// Loop through associative array in the form of key and value
foreach($array as $key => $value)
{
// If the value is array data type or not
if (gettype($value) != 'array')
{
// if true, just print the value
echo "$value";
}
else
{
// call recursive function
print_array($value);
}
}
}
寫遞歸功能?! – Rizier123
@ Rizier123你能解釋一下如何編寫遞歸函數嗎? –
也給出預期的輸出還有 – Dan