📜  cara membuat 循环表 dengan php (1)

📅  最后修改于: 2023-12-03 14:40:01.356000             🧑  作者: Mango

使用PHP创建循环表

在PHP中,我们可以使用数组或循环语句来创建循环表。下面我们将逐步介绍如何使用PHP创建一个循环表。

创建一个基本的循环表

我们可以使用PHP的 for 循环语句来创建一个数字循环表,例如:

<?php
  $numbers = array();

  for ($i = 1; $i <= 10; $i++) {
    $numbers[] = $i;
  }

  print_r($numbers);
?>

运行以上代码,将会在屏幕上输出一个包含数字1到10的数组。

创建一个关联型循环表

我们可以使用PHP的 foreach 循环语句来创建一个关联型循环表,例如:

<?php
  $employees = array(
    array("name" => "John", "age" => 30, "job" => "Manager"),
    array("name" => "Mary", "age" => 25, "job" => "Sales"),
    array("name" => "Bob", "age" => 40, "job" => "Accounting")
  );

  foreach ($employees as $key => $value) {
    echo "Employee " . ($key+1) . ": " . $value["name"] . ", " . $value["age"] . " years old, " . $value["job"] . "<br>";
  }
?>

运行以上代码,将会在屏幕上输出如下结果:

Employee 1: John, 30 years old, Manager
Employee 2: Mary, 25 years old, Sales
Employee 3: Bob, 40 years old, Accounting
嵌套循环表

我们可以使用嵌套循环语句来创建一个嵌套型循环表,例如:

<?php
  $products = array(
    array("name" => "Apple", "prices" => array(0.5, 0.6, 0.7)),
    array("name" => "Banana", "prices" => array(0.3, 0.4)),
    array("name" => "Orange", "prices" => array(0.6, 0.8, 1.0, 1.2)),
  );

  foreach ($products as $key => $value) {
    echo "Product " . ($key+1) . ": " . $value["name"] . "<br>";
    foreach ($value["prices"] as $price) {
      echo "- Price: $" . $price . "<br>";
    }
  }
?>

运行以上代码,将会在屏幕上输出如下结果:

Product 1: Apple
- Price: $0.5
- Price: $0.6
- Price: $0.7
Product 2: Banana
- Price: $0.3
- Price: $0.4
Product 3: Orange
- Price: $0.6
- Price: $0.8
- Price: $1.0
- Price: $1.2

至此,我们已经学会了使用PHP创建循环表。