Usage and instance of foreach in PHP

Source: Internet
Author: User
Foreach is often used in PHP, and arrays must be used to use foreach. Therefore, in this article, we talk about arrays and foreach. Foreach is often used in PHP, and arrays must be used to use foreach. Therefore, in this article, we talk about arrays and foreach.

Foreach has two syntaxes:

First, traverse the given array statement array_expression array. In each loop, the value of the current unit is assigned to $ value and the pointer inside the array moves forward (so the next unit will be obtained in the next loop ).

foreach (array_expression as $value)    statement

Type 2: Same as above. The key name of the current unit is also assigned to the variable $ key in each loop.

foreach (array_expression as $key => $value)    statement

Let's explain it one by one!

I. one-dimensional common array and foreach

We first write a one-dimensional array, as shown below:

$a = array('Tom','Mary','Peter','Jack');

1. We use the first foreach method for output.

foreach ($a as $value) {    echo $value."
";}

The final result is:

TomMaryPeterJack

2. we use the second foreach method for output.

foreach ($a as $key => $value) {    echo $key.','.$value."
";}

The final result is:

0, Tom

1, Mary

2, Peter

3, Jack

Conclusion: Obviously, we can see that there is only one more $ key, and the value of this $ key is number 1, 2, 3, 4, and so on!

2. one-dimensional join array and foreach

One-dimensional join arrays are as follows:

$b = array('a'=>'Tom','b'=>'Mary','c'=>'Peter','d'=>'Jack');

Some people love to write this as follows:

$b = array(    'a'=>'Tom',    'b'=>'Mary',    'c'=>'Peter',    'd'=>'Jack');

1. We use the first foreach method to output the same information as above.

foreach ($b as $value) {    echo $value."
";}

The final result is:

TomMaryPeterJack

2. we use the second foreach method for output.

foreach ($b as $key => $value) {    echo $key.','.$value."
";}

The final result is:

a,Tomb,Maryc,Peterd,Jack

Conclusion: Obviously, in a one-dimensional join array, $ key is the associated sequence number, that is, the corresponding a, B, c, and d.

3. two-dimensional common array and foreach

It is a little troublesome to traverse two-dimensional arrays. why? The retrieved value is an array. since it is an array, you can perform various operations on the array!

Let's first look at a basic two-dimensional array, as shown below

$c = array(    array('1','Tom'),    array('2','Mary'),    array('3','Peter'),    array('4','Jack'));

1. we adopt the first foreach method:

foreach ($c as $value) {    print_r($value);    echo "
";}

The following result is displayed:

Array ( [0] => 11 [1] => Tom )Array ( [0] => 22 [1] => Mary )Array ( [0] => 33 [1] => Peter )Array ( [0] => 44 [1] => Jack )

2. we adopt the second foreach method:

foreach ($c as $key => $value) {    echo '$key='.$key."
"; print_r($value); echo "
";}

The following result is displayed:

$key=0Array ( [0] => 11 [1] => Tom )$key=1Array ( [0] => 22 [1] => Mary )$key=2Array ( [0] => 33 [1] => Peter )$key=3Array ( [0] => 44 [1] => Jack )

Conclusion: We can see from the above that the basic two-dimensional array, $ key is the serial number, such as 0 \ 1 \ 2 \ 3, and so on!

4. associate two-dimensional arrays with foreach

Note: joining a two-dimensional array can be used more in actual projects. Why? Generally, the data extracted from the database is associated with a two-dimensional array. after learning to associate a two-dimensional array, we have mastered a large part in PHP practice!

List the associated two-dimensional arrays first, as shown below:

$d = array(    array('id'=>'11','name'=>'Tom'),    array('id'=>'22','name'=>'Mary'),    array('id'=>'33','name'=>'Peter'),    array('id'=>'44','name'=>'Jack'));

1. Use the code in the first method:

foreach ($d as $value) {    print_r($value);    echo "
";}

The result is as follows:

Array ( [id] => 11 [name] => Tom )Array ( [id] => 22 [name] => Mary )Array ( [id] => 33 [name] => Peter )Array ( [id] => 44 [name] => Jack )

Obviously, the difference between association and non-association is that the frontend side is 0/1, and so on, while the association displays the specific name id/name.

2. code using the second method:

foreach ($d as $key => $value) {    echo '$key='.$key."
"; print_r($value); echo "
";}

The result is as follows:

$key=0Array ( [id] => 11 [name] => Tom )$key=1Array ( [id] => 22 [name] => Mary )$key=2Array ( [id] => 33 [name] => Peter )$key=3Array ( [id] => 44 [name] => Jack )

Summary: $ key is still 0/1/2/3.

5. practical application in the project

Note: in the project, the array changes a lot. of course, foreach is indispensable! You can also use the while, each, and other methods, but foreach is the most convenient! Below we will briefly discuss several common project practices!

Practice 1: Change a two-dimensional joined array to a one-dimensional normal array

Or fourth, list the associated two-dimensional arrays, as shown below:

$d = array(    array('id'=>'11','name'=>'Tom'),    array('id'=>'22','name'=>'Mary'),    array('id'=>'33','name'=>'Peter'),    array('id'=>'44','name'=>'Jack'));

Now we only need the content in the name column. of course, we can use the following methods to implement it,

foreach ($d as $key => $value) {    echo ($value['name']);    echo "
";}

But sometimes we have to column it as a one-dimensional array, so we have the following method:

// Obtain the name column as a one-dimensional array $ nameArr = array (); // name column foreach ($ d as $ key => $ value) {$ nameArr [] = $ value ['name'];} print_r ($ nameArr );

In the preceding example, a new array is obtained by assigning an empty array value. The foreach empty array is equal to our value! The result of the above code is as follows:

Array(    [0] => Tom    [1] => Mary    [2] => Peter    [3] => Jack)

This array is obviously a one-dimensional normal array, as shown below:

$d = array('Tom','Mary','Peter','Jack');

Now, we have written the two-dimensional joined array into a one-dimensional normal array!

Practice 2: Level 2 Classification and unlimited classification

Obviously, the data we get from the database is a two-dimensional array and a two-dimensional associated array. So how can we retrieve the parent category? How can I retrieve the subcategory of the corresponding parent category?

The first thing to note is that almost all classifications are in a database mode. Therefore, we need to know its structure and how to retrieve the corresponding data!

For the second-level classification, I will find a better example on the Internet, that is, "news classification".

Okay, you don't have to talk about it. let's get started! Write an array first.

// Category data retrieved from the database $ original_array = array ('id' => 1, 'pid' => 0, 'name' => 'news category'), array ('id' => 2, 'pid '=> 0, 'name' => 'latest ads '), array ('id' => 3, 'pid '=> 1, 'name' => 'domestic News'), array ('id' => 4, 'pid '=> 1, 'name' => 'International news'), array ('id' => 5, 'pid '=> 0, 'name' => 'image category'), array ('id' => 6, 'pid '=> 5, 'name' => 'news image '), array ('id' => 7, 'pid '=> 5, 'name' => 'Other image '));

At the same time, the database looks like this.

Note: This is the classification of databases! The retrieved array looks like this! This is generally the case!

// Category data retrieved from the database $ original_array = array ('id' => 1, 'pid' => 0, 'name' => 'news category'), array ('id' => 2, 'pid '=> 0, 'name' => 'latest ads '), array ('id' => 3, 'pid '=> 1, 'name' => 'domestic News'), array ('id' => 4, 'pid '=> 1, 'name' => 'International news'), array ('id' => 5, 'pid '=> 0, 'name' => 'image category'), array ('id' => 6, 'pid '=> 5, 'name' => 'news image '), array ('id' => 7, 'pid '=> 5, 'name' => 'Other image '));

First, we need to know what the expected results look like? This: we need to know! (In the past, I did not know much about this and often used open-source programs. as a result, I did not write much about this)

The final result we want is like this! (Not afraid of jokes. I asked a friend to help me solve this problem !)

// Sorted classification data $ output_array = array ('id' => 1, 'pid' => 0, 'name' => 'news category ', 'Children '=> array ('id' => 3, 'pid' => 1, 'name' => 'domestic News '), array ('id' => 4, 'pid '=> 1, 'name' => 'International news'), array ('id' => 2, 'pid '=> 0, 'name' => 'latest ads',), array ('id' => 5, 'pid' => 0, 'name' => 'image category', 'Children '=> array ('id' => 6, 'pid' => 5, 'name' => 'news image'), array ('id' => 7, 'pid '=> 5, 'name' => 'Other image '),),),);

Obviously, a field is added to the array, that is, children!

How can I change from $ original_array to $ output_array? Here is a function made by a friend of mine, and foreach is also used!

The function is as follows:

// Sorting function/*** generates an infinite tree algorithm * @ author Yaoyu 2014-04-01 * @ param array $ arr input array * @ param number $ pid root-level pid * @ param string $ column_name column name, id | pid parent id | key name of the children sub-array * @ return array $ ret */function make_tree ($ arr, $ pid = 0, $ column_name = 'Id | pid | children ') {list ($ idname, $ pidname, $ cldname) = explode (' | ', $ column_name ); $ ret = array (); foreach ($ arr as $ k => $ v) {if ($ v [$ pidname] = $ pid) {$ tmp = $ arr [$ k]; unset ($ arr [$ k]); $ tmp [$ cldname] = make_tree ($ arr, $ v [$ idname], $ column_name); $ ret [] = $ tmp;} return $ ret ;}

How can we use it?

// Use the sorting function $ output_array = make_tree ($ original_array );

The Complete usage is as follows:

$output_array =make_tree($arr, 0,  'id|pid|children')

After the function is called, we get the first-level and second-level categories!

foreach ($output_array as $key => $value) {    echo ''.$value['name'].'';    foreach ($value['children'] as $key => $value) {        echo $value['name'].',';}

The result is as follows:

Appendix: $ output_array. use print_r to obtain the following result!

Array ([0] => Array ([id] => 1 [pid] => 0 [name] => News classification [children] => Array ([0] => array ([id] => 3 [pid] => 1 [name] => Chinese News [children] => Array ()) [1] => Array ([id] => 4 [pid] => 1 [name] => International News [children] => Array ()))) [1] => Array ([id] => 2 [pid] => 0 [name] => Latest announcement [children] => Array ()) [2] => Array ([id] => 5 [pid] => 0 [name] => image classification [children] => Array ([0] => Array ([id] => 6 [pid] => 5 [name] => News image [children] => Array ()) [1] => Array ([id] => 7 [pid] => 5 [name] => Other Images [children] => Array ()))))

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.