Usage of foreach in PHP

Source: Internet
Author: User
This article describes the use and examples of foreach in PHP, details the use of foreach, and the interested partners can refer to it.

The use of foreach is often used in PHP, and it is necessary to use a foreach array. So, in this article, we're talking about arrays while we talk about foreach.

foreach has two types of syntax:

The first: Iterate over the given array statement array_expression array. In each loop, the value of the current cell is assigned to the $value and the pointer inside the array is moved forward one step (so the next cell in the next loop will be taken).

foreach (array_expression as $value)

The second type: Ditto, and the key name of the current cell is assigned to the variable $key in each loop.

foreach (array_expression as $key = $value)

Below we hit explain!

One or one-D normal array with foreach

Let's start by writing a one-dimensional array, as follows:

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

1, we use the first kind of the Foreach method to output.

foreach ($a as $value) {  echo $value. <br/> ";}

The final result is:

Tom
Mary
Peter
Jack

2, we use the second kind of foreach method to output.

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

The final result is:

0,tom
1,mary
2,peter
3,jack

Summary: Obviously, we see just one more $key, and this $key value is the number 1, 2, 3, 4, and so on!

Two or one-D associative arrays and foreach

One-dimensional associative arrays are as follows:

$b = Array (' A ' = ' Tom ', ' b ' = ' Mary ', ' c ' = ' Peter ', ' d ' = ' "Jack ');

There are those who love to write like this:

$b = Array (  ' a ' = ' Tom ',  ' b ' = ' Mary ',  ' c ' = ' Peter ',  ' d ' = ' "Jack ');

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

foreach ($b as $value) {  echo $value. <br/> ";}

The final result is:

Tom
Mary
Peter
Jack

2, we use the second kind of foreach method to output.

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

The final result is:

A,tom
B,mary
C,peter
D,jack

Summary: It is clear that in a one-dimensional associative array, the $key is the associated ordinal number, which corresponds to a, B, C, D.

Three or two-D normal array with foreach

When traversing a two-dimensional array, it's a little more troublesome. Because the value that is traversed is an array, and since it is an array, you can do all kinds of operations on the arrays!

Let's first look at a basic two-dimensional array, as follows:

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

1. We use the first method of foreach:

foreach ($c as $value) {  print_r ($value);  echo "<br/>";}

To get this result:

Array ([0] = = [1] = Tom)
Array ([0] = [1] = Mary)
Array ([0] = [1] = Peter)
Array ([0] = [1] = + Jack)

2. We use the second method of foreach:

foreach ($c as $key = + $value) {  echo ' $key = '. $key. " <br/> ";  Print_r ($value);  echo "<br/>";}

Get the following results:

$key =0
Array ([0] = = [1] = Tom)
$key =1
Array ([0] = [1] = Mary)
$key =2
Array ([0] = [1] = Peter)
$key =3
Array ([0] = [1] = + Jack)

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

Iv. associative two-dimensional arrays and foreach

Indicates that the associated two-dimensional array is used more in the actual project. Why? The data extracted from the general database are related to two-dimensional arrays, learned the associative two-dimensional array, in the actual practice of PHP, has mastered a large part of it!

Then the associative two-dimensional arrays are listed as follows:

$d = array (' id ' = ' = '  , ' name ' = ' Tom '), array (  ' id ' = ' + ', ' name ' = ' Mary '),  Array (' id ' = ' + ', ' name ' = + ' Peter ',  array (' id ' = ' + ', ' name ' = ' Jack ') ');

1, the first method of code:

foreach ($d as $value) {  print_r ($value);  echo "<br/>";}

The results are as follows:

Array ([id] = [name] = Tom)
Array ([id] = [name] + Mary)
Array ([id] = [name] = Peter)
Array ([id] = [name] = + Jack)

Obviously, the difference between Association and non-association is that it is not related to the front is 0/1 and so on, and the association shows the specific name Id/name and so on.

2, the code of the second method:

foreach ($d as $key = + $value) {  echo ' $key = '. $key. " <br/> ";  Print_r ($value);  echo "<br/>";}

The results are as follows:

$key =0
Array ([id] = [name] = Tom)
$key =1
Array ([id] = [name] + Mary)
$key =2
Array ([id] = [name] = Peter)
$key =3
Array ([id] = [name] = + Jack)

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

V. Practical application in the project

Description: In the project, the array changes a lot, of course, the foreach work is not! Of course, you can use while, each and so on, but foreach is the most convenient! Below briefly say a few common project actual combat!

Combat 1: Transform two-dimensional associative arrays into one-dimensional normal arrays

or the fourth list of associative two-dimensional arrays, as follows:

$d = array (' id ' = ' = '  , ' name ' = ' Tom '), array (  ' id ' = ' + ', ' name ' = ' Mary '),  Array (' id ' = ' + ', ' name ' = + ' Peter ',  array (' id ' = ' + ', ' name ' = ' Jack ') ');

Now we just have to name a column of content, of course, we can use the following methods to achieve,

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

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

Gets the name column as a one-dimensional array $namearr = array (); Name column foreach ($d as $key = = $value) {  $NAMEARR [] = $value [' name '];} Print_r ($NAMEARR);

Above by assigning an empty array value, the empty array of foreach equals our value, and we get a new array! The result of the above code is as follows:

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

This array is obviously: one-dimensional normal array, as follows:

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

Well, the two-dimensional associative array becomes a one-dimensional normal array and it's written here!

Combat 2: Level two classification and infinite class classification

Obviously, the data we take out of the database is a two-dimensional array and a two-dimensional associative array. So how do we take out the parent category? How do I remove the sub-categories of the corresponding parent category?

The first thing to say is that almost all of the classifications are a database schema, so it is very necessary to understand its structure, and how to take out the corresponding data!

For the level two classification, for the sake of convenience, I find a better example from the Internet, that is, "News classification"!

All right, no more nonsense, get to the point! Let's write an array first.

Classification data removed from the database $original_array = array (' id ' = =  1, ' pid ' = = 0, ' name ' = ' news category '),  array (' id ' = 2 , ' pid ' = 0, ' name ' = ' latest announcement '),  array (' id ' = = 3, ' pid ' = 1, ' name ' = ' Domestic News '),  array (' id ' = + 4, ' pi d ' + 1, ' name ' = ' International News '),  array (' id ' = + 5, ' pid ' = 0, ' name ' = ' picture '),  array (' id ' = = 6, ' pid ' = > 5, ' name ' = ' news image '),  array (' id ' = = 7, ' pid ' = 5, ' name ' = ' other picture '));

At the same time, the database is like this.

Description: The classification of the database is like this! The array that was taken out is also this way! In general!

The categorical data removed from the database $original_array = Array (  ' id ' = =    1,    ' pid ' = = 0,    ' name ' = ' news category '  ), C5/>array (    ' id ' = = 2,    ' pid ' = + 0,    ' name ' = ' latest announcement '  ),  array (    ' id ' = 3,    ' PID ' = 1,    ' name ' = ' Domestic News '  ),  array (    ' id ' = = 4,    ' pid ' = 1,    ' name ' = ' = ') International News '  ),  array (    ' id ' = = 5,    ' pid ' = + 0,    ' name ' = ' picture category '  ),  array (    ' ID ' = 6,    ' pid ' = + 5,    ' name ' = ' news image '  ,  array (    ' id ' = 7,    ' pid ' = ' = ' + 5,
   ' name ' = ' other pictures ')  ;

So first we need to know what we want to look like? This: we need to know! (I used to know less about this aspect, and often use open source programs, so I do not how to write this aspect)

The end result we want is this! (Not afraid of everyone jokes, this point I asked a friend to help to solve the busy!) )

Sorted 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 announcement ', ', '  array (    ' id ' = = 5,    ' pid ' = 0,    ' name ') = = ' picture category ',    ' children ' = = Array (        ' id ' = = 6,        ' pid ' = + 5,        ' name ' = ' news image ') c31/>),      array (        ' id ' = = 7,        ' pid ' = = 5,        ' name ' = ' other pictures '      )  ,),);

Obviously, there is one more field in the array, which is children!

So how do you change from $original _array to $output _array? Here is a function of a friend of mine, of course, also used to foreach!

The functions are as follows:

Collation function/** * Generate infinite-level tree algorithm * @author baiyu 2014-04-01 * @param array $arr        input array * @param number $pid        pid of the root level * @param stri  ng $column _name    column name, id|pid the name of the parent ID |children the key name of the 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 do they use it?

The use of the collation function $output_array = Make_tree ($original _array);

The complete use method is as follows:

$output _array =make_tree ($arr, 0, ' Id|pid|children ')

function, we get the first class classification and class two classification with this call!

foreach ($output _array as $key = + $value) {  echo ' 

The results are as follows:

Attached: $output _array This array, we use Print_r, we can get the following results!

Array ([0] = = Array ([id] = 1 [pid] = 0 [name] + news category [Children] + = array ([0] = = Array ([id] = 3 [PID] = 1 [name] + = Country            Inside news [Children] = = Array ()) [1] = = Array                 ([id] = 4 [PID] + 1 [name] + international news [children] = = Array      ()))) [1] = = Array ([id] + 2 [pid] = 0 [Name] and the latest announcement [children] = = Array ()) [2] = = Array ([ID] + 5 [PID ] = 0 [name] + = picture Category [Children] = = Array ([0] = = Array ([                 ID] = 6 [PID] + 5 [name] + news Image [Children] + = Array (       )     ) [1] = = Array ([id] = 7 [PID] = 5 [name] =&gt ; Other images [children] = = Array ()))))

Summary: The above is the whole content of this article, I hope that everyone's learning has helped. At the same time also hope that we support topic.alibabacloud.com.

Related Article

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.