Menu
CoddyTech

标记任务为已完成

本课属于 Coddy PHP 学习旅程的“基础知识”单元。第 57 课,共 71 课。

challenge icon

挑战

简单

在上一课中,你显示了所有任务及其状态。现在,添加将特定任务标记为已完成的功能。

读取 4 行任务描述输入(和之前一样,包括 3 个初始任务和 1 个新任务)。然后读取第 5 个输入:一个表示要标记为已完成的任务索引的整数(从 0 开始)。

用全部 4 个任务构建 $todos 数组后,将指定索引处任务的 "completed" 值更新为 true。

然后遍历数组,并按以下格式打印每个任务:

  • 如果任务已完成:- [task description] (Done)
  • 如果任务尚未完成:- [task description] (Pending)

每个任务单独打印一行。

示例:

如果输入是 Buy groceries、Walk the dog、Finish homework、Call mom 和 1,输出应为:

- Buy groceries (Pending)
- Walk the dog (Done)
- Finish homework (Pending)
- Call mom (Pending)

如果输入是 Clean room、Read book、Exercise、Cook dinner 和 3,输出应为:

- Clean room (Pending)
- Read book (Pending)
- Exercise (Pending)
- Cook dinner (Done)

亲手试试

<?php
// Read three task descriptions
$task1 = trim(fgets(STDIN));
$task2 = trim(fgets(STDIN));
$task3 = trim(fgets(STDIN));

// Read the new task to add
$newTask = trim(fgets(STDIN));

// Create a $todos array containing three task arrays
// Each task should be an associative array with "task" and "completed" keys
$todos = [
    ["task" => $task1, "completed" => false],
    ["task" => $task2, "completed" => false],
    ["task" => $task3, "completed" => false]
];

// Add the new task to the end of the array
$todos[] = ["task" => $newTask, "completed" => false];

// Loop through the array and print each task in the formatted list
foreach ($todos as $todo) {
    echo "- " . $todo["task"] . " (Pending)\n";
}
?>

基础知识中的所有课

自己练习: PHP 在线编译器