-
-
/**
- desc: array
- */
- $arr = array (
- "1" => 'test',
- '2' => 'me',
- array (
- "3" => "beij",
- "4" => "zz"
- ),
- "45",
- array (
- "5" => "5",
- "6" => " ewrwer",
- "7" => "ssss",
- array (
- "8" => "ssd",
- "9" => "bdex"
- ),
- "10",
- "11"
- )
- );
- ?>
-
Copy code
Next, write a recursive function to print this array:
-
-
/**
- desc: recursively traverse the array
- link: bbs.it-home.org
- date: 2013/2/22
- */
- function RecursiveArr($patten, $array) {
- foreach ( $array as $value ) {
- if (is_array ( $value )) {
- $patten = $patten . $patten;
- RecursiveArr ( $patten, $value );
- } else {
- echo "
" . $patten . "【" . key ( $array ) . "】" . ": " . $value . " " . " ";
- next ( $array ); / / After assigning a value to the key, you need to move to the next one before the key will be updated.
Call example:
-
-
-
RecursiveArr ( '-', $arr );
Copy the code
The result in the picture below appears:
As can be seen from the above running result diagram, some keys are found to be duplicated.
In order to compare the differences and connections, let’s look at the code next:
-
-
/**
desc: recursively traverse the array link: bbs.it-home.org date: 2013/2/22 */function RecursiveArr($patten, $array) { foreach ( $array as $value ) { if (is_array ( $value )) { - $patten = $patten . $patten;
- RecursiveArr ( $patten, $value );
- } else {
- echo "
" . $patten . "【" . key ( $array ) . "】" . ": " . $value . " " . " ";
- }
- next ( $array ) ; // After assigning a value to the key, you need to move to the next one before the key will be updated
- }
- }
-
-
- Copy code
-
-
- If I change the previous recursive function to the one above code, the running result diagram is as follows:
-
-
- You should be able to tell something from the two result pictures above, dear.
-
Instructions:
If the next() function is used in the if-else code segment in foreach, the order of different levels can be recorded and followed;
But if the next() function is used outside the if-else code segment in foreach, the order will increase directly without distinguishing levels.
Therefore, if you need to process key values, you need to pay special attention to the changes here, otherwise it may make you fly like a bullet... Ha!
|