Home Backend Development PHP Tutorial How to use foreach in PHP

How to use foreach in PHP

May 31, 2018 am 11:49 AM
foreach php usage

This article introduces the usage and examples of foreach in PHP, and introduces the usage of foreach in detail. Interested friends can refer to it.

Related recommendations: php complete self-study manual, PHP online training class

often used in PHP The use of foreach will be used, and to use foreach, you must use an array. Therefore, in this article, we will talk about arrays and foreach at the same time.

foreach has two syntaxes:

The first one: traverse the given array statement array_expression array. Each time through the loop, the value of the current cell is assigned to $value and the pointer inside the array is moved forward one step (so the next cell will be obtained in the next loop).

foreach (array_expression as $value)
Copy after login

Second type: Same as above. At the same time, the key name of the current unit will also be assigned to the variable $key in each loop.

foreach (array_expression as $key => $value)
Copy after login

Let’s explain them one by one below!

1. One-dimensional ordinary array and foreach

We first write a one-dimensional array, as follows:

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

1. We use the first one foreach method to output.

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

The final result is:

Tom
Mary
Peter
Jack

2. We use the second foreach method to output.

foreach ($a as $key => $value) {
  echo $key.&#39;,&#39;.$value."<br/>";
}
Copy after login

The final result is:

0,Tom
1,Mary
2,Peter
3,Jack

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

2. One-dimensional associative array and foreach

The one-dimensional associative array is as follows:

$b = array(&#39;a&#39;=>&#39;Tom&#39;,&#39;b&#39;=>&#39;Mary&#39;,&#39;c&#39;=>&#39;Peter&#39;,&#39;d&#39;=>&#39;Jack&#39;);
Copy after login

Some people also like to write this , as follows:

$b = array(
  &#39;a&#39;=>&#39;Tom&#39;,
  &#39;b&#39;=>&#39;Mary&#39;,
  &#39;c&#39;=>&#39;Peter&#39;,
  &#39;d&#39;=>&#39;Jack&#39;
);
Copy after login

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

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

The final result is:

Tom
Mary
Peter
Jack

2. We use the second foreach method to output.

foreach ($b as $key => $value) {
  echo $key.&#39;,&#39;.$value."<br/>";
}
Copy after login

The final result is:

a,Tom
b,Mary
c,Peter
d,Jack

Summary: Obviously, in a one-dimensional associative array, $key is the associated serial number, that is, the corresponding a, b, c, d.

Recommended related video tutorials:
Chapter video tutorial "Using foreach loop to traverse: Index and associative arrays"
Source course " Dugu Jiujian (4)_PHP video tutorial

3. Two-dimensional ordinary array and foreach

When traversing a two-dimensional array, it is a little more troublesome, why Woolen cloth? Because the traversed 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 follows:

$c = array(
  array(&#39;1&#39;,&#39;Tom&#39;),
  array(&#39;2&#39;,&#39;Mary&#39;),
  array(&#39;3&#39;,&#39;Peter&#39;),
  array(&#39;4&#39;,&#39;Jack&#39;)
);
Copy after login

1. We use the first foreach method:

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

Get this result:

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

2. We use the second foreach method:

foreach ($c as $key => $value) {
  echo &#39;$key=&#39;.$key."<br/>";
  print_r($value);
  echo "<br/>";
}
Copy after login

The following results are obtained:

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

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

4. Associative two-dimensional arrays and foreach

Explain that associative two-dimensional arrays are used a lot in actual projects. Why? Generally, the data extracted from the database is associated with two-dimensional arrays. If you learn to associate two-dimensional arrays, you will have mastered a large part of it in actual PHP practice!

Then first list the associated two-dimensional array, as follows:

$d = array(
  array(&#39;id&#39;=>&#39;11&#39;,&#39;name&#39;=>&#39;Tom&#39;),
  array(&#39;id&#39;=>&#39;22&#39;,&#39;name&#39;=>&#39;Mary&#39;),
  array(&#39;id&#39;=>&#39;33&#39;,&#39;name&#39;=>&#39;Peter&#39;),
  array(&#39;id&#39;=>&#39;44&#39;,&#39;name&#39;=>&#39;Jack&#39;)
);
Copy after login
Copy after login

1. Use the first method code:

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

The result obtained 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 related and not related is: not related The front is 0/1 and so on, and the association shows the specific name id/name and so on.

2. Use the code of the second method:

foreach ($d as $key => $value) {
  echo &#39;$key=&#39;.$key."<br/>";
  print_r($value);
  echo "<br/>";
}
Copy after login

The results obtained are as follows:

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

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

5. Practical application in the project

Explanation: In the project, there are many changes in the array, and of course foreach contributes a lot! Of course, you can also use while, each, etc. methods, but foreach is the most convenient! Let’s briefly talk about some common project practices!

实战1:将二维关联数组变为一维普通数组

还是第四列出关联二维数组,如下:

$d = array(
  array(&#39;id&#39;=>&#39;11&#39;,&#39;name&#39;=>&#39;Tom&#39;),
  array(&#39;id&#39;=>&#39;22&#39;,&#39;name&#39;=>&#39;Mary&#39;),
  array(&#39;id&#39;=>&#39;33&#39;,&#39;name&#39;=>&#39;Peter&#39;),
  array(&#39;id&#39;=>&#39;44&#39;,&#39;name&#39;=>&#39;Jack&#39;)
);
Copy after login
Copy after login

现在我们只要 name 一列的内容,当然我们可以用以下的方法来实现,

foreach ($d as $key => $value) {
  echo ($value[&#39;name&#39;]);
  echo "<br/>";
}
Copy after login

但有时候我们不得不将之列为一个一维数组,于是我们就有了以下的方法:

//获取name列作为一维数组
$nameArr = array(); //name列
foreach ($d as $key => $value) {
  $nameArr[] = $value[&#39;name&#39;];
}
print_r($nameArr);
Copy after login

以上通过赋空数组值,foreach 这个空数组等于我们的值,就得到了一个新的数组!以上代码的结果如下:

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

这个数组明显是:一维普通数组,如下:

$d = array(&#39;Tom&#39;,&#39;Mary&#39;,&#39;Peter&#39;,&#39;Jack&#39;);
Copy after login

好了,将二维关联数组变为一维普通数组就写到了这里!

实战2 :二级分类以及无限级分类

很明显,我们从数据库中取出来的数据就是一个二维数组,而且是二维关联数组。那么,我们怎么取出父分类?怎么取出对应父分类的子分类呢?

首先要说明的是:几乎所有的分类都是一个数据库模式,因此我们十分有必要了解它的结构,还有怎么取出对应的数据!

对于二级分类,为了说明方便,我从网上找一个比较好说明的例子,那就是“新闻分类“!

好了,废话不多说,开始正题!我们先写一个数组。

//从数据库中取出的分类数据
$original_array = array(
  array(&#39;id&#39; => 1,&#39;pid&#39; => 0,&#39;name&#39; => &#39;新闻分类&#39;),
  array(&#39;id&#39; => 2,&#39;pid&#39; => 0,&#39;name&#39; => &#39;最新公告&#39;),
  array(&#39;id&#39; => 3,&#39;pid&#39; => 1,&#39;name&#39; => &#39;国内新闻&#39;),
  array(&#39;id&#39; => 4,&#39;pid&#39; => 1,&#39;name&#39; => &#39;国际新闻&#39;),
  array(&#39;id&#39; => 5,&#39;pid&#39; => 0,&#39;name&#39; => &#39;图片分类&#39;),
  array(&#39;id&#39; => 6,&#39;pid&#39; => 5,&#39;name&#39; => &#39;新闻图片&#39;),
  array(&#39;id&#39; => 7,&#39;pid&#39; => 5,&#39;name&#39; => &#39;其它图片&#39;)
);
Copy after login

同时,数据库是这个样子的。

说明:数据库的分类就是这个样子的!取出来的数组也是这个样子的!一般这样子的!

//从数据库中取出的分类数据
$original_array = array(
  array(
    &#39;id&#39; => 1,
    &#39;pid&#39; => 0,
    &#39;name&#39; => &#39;新闻分类&#39;
  ),
  array(
    &#39;id&#39; => 2,
    &#39;pid&#39; => 0,
    &#39;name&#39; => &#39;最新公告&#39;
  ),
  array(
    &#39;id&#39; => 3,
    &#39;pid&#39; => 1,
    &#39;name&#39; => &#39;国内新闻&#39;
  ),
  array(
    &#39;id&#39; => 4,
    &#39;pid&#39; => 1,
    &#39;name&#39; => &#39;国际新闻&#39;
  ),
  array(
    &#39;id&#39; => 5,
    &#39;pid&#39; => 0,
    &#39;name&#39; => &#39;图片分类&#39;
  ),
  array(
    &#39;id&#39; => 6,
    &#39;pid&#39; => 5,
    &#39;name&#39; => &#39;新闻图片&#39;
  ),
  array(
    &#39;id&#39; => 7,
    &#39;pid&#39; => 5,
    &#39;name&#39; => &#39;其它图片&#39;
  )
);
Copy after login

那么首先我们得知道我们想要的结果是什么样子呢?这一点:我们必要知道!(以前我对这方面了解比较不深,又常用开源程序,因此导致我不怎么会写这方面了)

我们最终想要的结果是这样子的!(不怕大家笑话,这一点我请一个朋友帮的忙才解决的!)

//整理后的分类数据
$output_array = array(
  array(
    &#39;id&#39; => 1,
    &#39;pid&#39; => 0,
    &#39;name&#39; => &#39;新闻分类&#39;,
    &#39;children&#39; => array(
      array(
        &#39;id&#39; => 3,
        &#39;pid&#39; => 1,
        &#39;name&#39; => &#39;国内新闻&#39;
      ),
      array(
        &#39;id&#39; => 4,
        &#39;pid&#39; => 1,
        &#39;name&#39; => &#39;国际新闻&#39;
      ),
    ),
  ),
  array(
    &#39;id&#39; => 2,
    &#39;pid&#39; => 0,
    &#39;name&#39; => &#39;最新公告&#39;,
  ),
  array(
    &#39;id&#39; => 5,
    &#39;pid&#39; => 0,
    &#39;name&#39; => &#39;图片分类&#39;,
    &#39;children&#39; => array(
      array(
        &#39;id&#39; => 6,
        &#39;pid&#39; => 5,
        &#39;name&#39; => &#39;新闻图片&#39;
      ),
      array(
        &#39;id&#39; => 7,
        &#39;pid&#39; => 5,
        &#39;name&#39; => &#39;其它图片&#39;
      ),
    ),
  ),
);
Copy after login

很明显,这里数组多了一个字段,就是 children!

那么,怎么 从 $original_array 变为 $output_array呢?这里有我一个朋友做的函数,当然也用到 foreach!

函数如下:

//整理函数
/**
 * 生成无限级树算法
 * @author Baiyu 2014-04-01
 * @param array $arr        输入数组
 * @param number $pid        根级的pid
 * @param string $column_name    列名,id|pid父id的名字|children子数组的键名
 * @return array $ret
 */
function make_tree($arr, $pid = 0, $column_name = &#39;id|pid|children&#39;) {
  list($idname, $pidname, $cldname) = explode(&#39;|&#39;, $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;
}
Copy after login

那们怎么使用呢?

//整理函数的使用
$output_array = make_tree($original_array);
Copy after login

完整使用方法如下:

$output_array =make_tree($arr, 0, &#39;id|pid|children&#39;)
Copy after login

函数之后,我们这样调用就得到了一级分类与二级分类!

foreach ($output_array as $key => $value) {
  echo &#39;<h2>&#39;.$value[&#39;name&#39;].&#39;</h2>&#39;;
  foreach ($value[&#39;children&#39;] as $key => $value) {
    echo $value[&#39;name&#39;].&#39;,&#39;;
}
Copy after login

结果如下:

附:$output_array 这个数组,我们使用print_r,就可以得到如下的结果!

Array
(
  [0] => Array
    (
      [id] => 1
      [pid] => 0
      [name] => 新闻分类
      [children] => Array
        (
          [0] => Array
            (
              [id] => 3
              [pid] => 1
              [name] => 国内新闻
              [children] => Array
                (
                )

            )

          [1] => Array
            (
              [id] => 4
              [pid] => 1
              [name] => 国际新闻
              [children] => Array
                (
                )

            )

        )

    )

  [1] => Array
    (
      [id] => 2
      [pid] => 0
      [name] => 最新公告
      [children] => Array
        (
        )

    )

  [2] => Array
    (
      [id] => 5
      [pid] => 0
      [name] => 图片分类
      [children] => Array
        (
          [0] => Array
            (
              [id] => 6
              [pid] => 5
              [name] => 新闻图片
              [children] => Array
                (
                )

            )

          [1] => Array
            (
              [id] => 7
              [pid] => 5
              [name] => 其它图片
              [children] => Array
                (
                )

            )

        )

    )

)
Copy after login

总结:以上就是本文的全部内容,希望对大家的学习有所帮助。同时也希望大家多多支持PHP中文网。

相关推荐:

PHP+ajax实现的省市联动功能

php命名空间使用详解

php+mysql实现广告点击统计(附代码)

The above is the detailed content of How to use foreach in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles