Explain the use of foreach in PHP and the example _php tips

Source: Internet
Author: User
Tags arrays

The use of foreach is often used in PHP, and if you use foreach, you must use an array. So in this article, we talk about the array, and we're talking about foreach.

foreach has two kinds of syntax:

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 moves forward one step (so the next cell will be taken in the next loop).

foreach (array_expression as $value)  

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

foreach (array_expression as $key => $value)  

Below we Yi Yilai explain!

One or one-D normal array with foreach

Let's write a one-dimensional array, as follows:

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

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

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

The final results are:

Tom
Mary
Peter
Jack

2, we use the second foreach method to output.

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

The final results are:

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

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

Two or one-D associative arrays and foreach

The one-dimensional associative array is as follows:

$b = Array (' A ' => ' Tom ', ' B ' => ' Mary ', ' C ' => ' Peter ', ' d ' => ' Jack ');

Others 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 as the top.

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

The final results are:

Tom
Mary
Peter
Jack

2, we use the second foreach method to output.

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

The final results are:

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

Summary: Obviously, in a one-dimensional associative array, $key is the ordinal number of the association, that is, the corresponding A, B, C, D.

Three or two-D normal array with foreach

When traversing a two-dimensional array, a little bit of trouble, why? Because the value of the traversal, is an array, since it is an array, you can do a variety of operations on the group!

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

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

1. We adopt 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 adopt the second method of foreach:

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

The following results are obtained:

$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!

Associative two-dimensional arrays and foreach

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

Then the associated two-dimensional array is listed first, 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 obtained are as follows:

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

Obviously, the difference between an association and an unrelated one is that it is not associated with 0/1, and so on, and the association displays the specific name id/name and so on.

2, with the second method of code:

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

The results obtained 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. The actual application of the project

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

Combat 1: Transform a two-dimensional associative array into one-dimensional normal array

Or fourth lists the associated 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 need to name a column of content, of course we can use the following methods to implement,

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 '];< c4/>}
Print_r ($NAMEARR);

Above by assigning an empty array value, this empty array of foreach equals our value, and we get a new array! The results of the above code are 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 into a one-dimensional normal array is written here!

Combat 2: Level two classification and unlimited 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 remove the parent category? How do I take out the subcategories of the parent category?

The first thing to say is that almost all categories 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, in order to illustrate the convenience, I look for a better description of the online example, that is, "News classification"!

Okay, no more nonsense, start the business! Let's write an array first.

Sorted data removed from the database
$original _array = Array (
  ' id ' => 1, ' pid ' => 0, ' name ' => ' News Classification '),
  array (' id ' =  > 2, ' pid ' => 0, ' name ' => ' latest Bulletin '),
  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 Picture '),
  array (' ID ' => 7, ' PID ' => 5, ' name ' => ' other Pictures ')
);

At the same time, the database is like this.

Description: The classification of the database is like this! The array was taken out of the same way! It's the usual!

Sorted data removed from the database
$original _array = Array (
    ' id ' => 1,
    ' pid ' => 0,
    ' name ' => ' News classification ')
  ),
  array (
    ' id ' => 2,
    ' pid ' => 0,
    ' name ' => ' latest Bulletin '
  ),
  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 picture '
  ),
  array (
    ' id ' => 7,
    ' pid ' = > 5,
    ' name ' => ' other pictures '
  )
;

So first we need to know what the result is like? This: we need to know! (I didn't know much about this before, and I used open source programs, so I didn't write about it.)

We finally want the result to be like this! (Not afraid of everyone jokes, this point I ask a friend to help the busy to solve!) )

Sorted data
$output _array = Array (
    ' id ' => 1,
    ' pid ' => 0, '
    name ' => ' news classification ',
    ' Children ' => Array (
      array (
        ' ID ' => 3,
        ' pid ' => 1,
        ' name ' => ' domestic News '
      ),
      Array (
        ' ID ' => 4,
        ' pid ' => 1,
        ' name ' => ' International News '),),
  Array (
    ' id ' => 2 ,
    ' pid ' => 0,
    ' name ' => ' latest Bulletin ',
  ),
  array (
    ' id ' => 5,
    ' pid ' => 0,
    ' name ' => ' Image classification ',
    ' children ' => Array (
      array (
        ' id ' => 6,
        ' PID ' => 5,
        ' name ' => ' news picture ') c33/>),
      array (
        ' id ' => 7,
        ' PID ' => 5,
        ' name ' => ' other pictures '
),),);

Obviously, there's 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, to use foreach!

The functions are as follows:

organizing function
/**
 * Generating infinite-level tree algorithm
 * @author baiyu 2014-04-01
 * @param array $arr        input array
 * @param number $pid c7/> root-level PID
 * @param string $column _name    column name, id|pid the name of the parent ID |children the key name of the child array
 * @return Array $ret/
function Make_tree ($arr, $pid = 0, $column _name = ' Id|pid|children ') {
  list ($idname, $pidname, $cldname) = Expl Ode (' | ', $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 usage is as follows:

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

function, we get the first class classification and class two classification by 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 classification [children] => ARR
              Ay ([0] => Array ([id] => 3 [PID] => 1 [Name] => domestic 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] => picture category [Children] => Array (  [0] => Array ([id] => 6 [PID] => 5 [name] => News pictures [ChiLdren] => Array () [1] => Array (
                [ID] => 7 [PID] => 5 [name] => other pictures [children] => Array

 (
                )

            )

        )

    )

)

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.