PHP中多維數組的遍歷可以使用嵌套循環來實現。以下是幾種常見的方法:
<?php
$multiArray = array(
array("apple", "banana", "cherry"),
array("dog", "cat", "elephant"),
array("red", "green", "blue")
);
foreach($multiArray as $array) {
foreach($array as $element) {
echo $element . " ";
}
echo "<br>";
}
?>
輸出:
apple banana cherry
dog cat elephant
red green blue
<?php
$multiArray = array(
array("apple", "banana", "cherry"),
array("dog", "cat", "elephant"),
array("red", "green", "blue")
);
for($i = 0; $i < count($multiArray); $i++) {
for($j = 0; $j < count($multiArray[$i]); $j++) {
echo $multiArray[$i][$j] . " ";
}
echo "<br>";
}
?>
輸出與上述方法相同。
<?php
$multiArray = array(
array("apple", "banana", "cherry"),
array("dog", "cat", "elephant"),
array("red", "green", "blue")
);
function printElement($element) {
echo $element . " ";
}
array_walk_recursive($multiArray, 'printElement');
?>
輸出與上述方法相同。
無論使用哪種方法,都可以通過嵌套循環或遞歸函數來遍歷多維數組的每個元素,并進行相應的操作。