When I sign in for Cainiao, I will always use the Traversal function. I will explain the foreach details here.
When I sign in for Cainiao's learning, I will always use the Traversal function, and I will use the foreach function. here is a detailed example of foreach:
First, let's look at the first statement. this statement is relatively simple. array_expression refers to an array expression. the as $ val statement obtains the values of this array in sequence and saves them to the $ val variable, in this method, only values in the array can be obtained, but the subscript index value of the array cannot be obtained. For example:
$ MyArray = array ("1" => "val1", "2" => "val2", "3" => "val3 ");
Foreach ($ myArray as $ val ){
Print ($ val ."");
}
The result will be output: val1 val2 val3
Let's take a look at the second format. in addition to getting the values of elements in the array, the second format can also get the index values of elements and save them to the $ key variable, if the index value of the array is not manually set, the default value is returned,
Look at the positive example:
Let's first look at a simple one-dimensional array:
$ MyArray = array ("1" => "val1", "2" = "val2", "3" => "val3 ");
Foreach ($ myArray as $ key => $ val ){
Print ($ key. "=>". $ val .";");
}
The program will output: 1 => val1; 2 => val2; 3 => val3;. Next let's look at a complex two-dimensional array traversal. The program is as follows:
$ MyArray = array (
"1" => array ("11" => "val11", "12" => "val12", "13" => "val13 "),
"2" => array ("21" => "val21", "22" => "val22", "23" => "val23 "),
"3" => array ("31" => "val31", "32" => "val32", "33" => "val33 ")
);
Print ("
");
Foreach ($ myArray as $ key => $ val ){
Print ("
- ". $ Key ."
");
If (is_array ($ val) {// checks whether the $ val value is an array. if yes, it goes to the lower-layer traversal.
Print ("
");
Foreach ($ val as $ key => $ val ){
Print ("
- ". $ Key." => ". $ val ."
");
}
Print ("
");
}
}
Print ("
");
Output result:
- 1
- 11 => val11
- 12 => val12
- 13 => val13
- 2
- 21 => val21
- 22 => val22
- 23 => val23
- 3
- 31 => val31
- 32 => val32
- 33 => val33
And
- A label is used to display solid and hollow dots.
Because the above is a two-dimensional array, the $ val value obtained after the first traversal will be an array, so I added a judgment in the traversal to traverse the two-layer array. Let's take a closer look. it's easy to understand. Don't be scared by the messy characters above. If conditions are met, you can copy them to the local phpserver and run them to check the results and analyze them. This makes it easier to understand.