gpt4 book ai didi

php - 如何多次回显一个字母,为每个新打印更改其中多个变量?

转载 作者:行者123 更新时间:2023-12-02 02:30:31 25 4
gpt4 key购买 nike

大家好!这是我在 stackoverflow 中的第一个问题,所以我希望我能够很好地遵守规则。 :)

对于我的 PHP 类(class),我有一个对我来说很困难的练习:其中包含大约 4 个变量的文本,所有变量都存储在数组中(每个变量一个数组,每个变量 3 个值)。每个数组的位置 [0] 位于第一个回显文本中,每个数组的位置 [1] 位于第二个文本中,依此类推。
如何使用数组中存储的所有值回显文本 3 次?在代码中我只能使用正文一次。

$u_name = array('student' => 'Joe','lecturer' => 'Kate', 'assistant' => 'Martin');
$course_name = array('PHP', 'CSS', 'HTML');
$role = array('student', 'lecturer', 'assistant');

echo "Hi," . $u_name['student'] . "! You've been approved to take part in course " . $course_name[0] . " as a " . $role[0] . ". The course " . $course_name[0] . " will last for two days.";
echo "<br>";
echo "Hi," . $u_name['lecturer'] . "! You've been approved to take part in course " . $course_name[1] . " as a " . $role[1] . ". The course " . $course_name[1] . " will last for two days.";
echo "<br>";
echo "Hi," . $u_name['assistant'] . "! You've been approved to take part in course " . $course_name[2] . " as a " . $role[2] . ". The course " . $course_name[2] . " will last for two days.";

这是我自己做的,但正如你在代码中看到的,我有正文的 3 倍。
先感谢您。

最佳答案

通常,您会使用某种类型的循环来遍历数组。

举几个循环类型:

  1. for
  2. while
  3. foreach

在这种情况下,最适合的就是 foreach 循环。

它只是遍历数组的每个元素,但因为你有一个 associative array和两个indexed array你还需要一个计数器。

$counter = 0;
foreach($u_name as $key=>$value){
echo "Hi, " . $value . "! You've been approved to take part in course " . $course_name[$counter] . " as a " . $role[$counter] . ". The course " . $course_name[$counter] . " will last for two days.";
echo "<br>";
$counter++;
}

如果还有任何问题,请随时提问。

关于php - 如何多次回显一个字母,为每个新打印更改其中多个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65105234/

25 4 0