Menu
CoddyTech

删除任务

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

challenge icon

挑战

简单

在上一课中,你将一个任务标记为已完成。现在,添加从列表中彻底删除任务的功能。

读取 4 行输入,内容为任务描述(3 个初始任务和 1 个新任务)。然后读取第 5 个输入:一个整数,表示要标记为已完成的任务索引。最后,读取第 6 个输入:一个整数,表示要从列表中删除的任务索引。

使用所有 4 个任务构建 $todos 数组,并将指定任务标记为已完成后,使用 array_splice() 删除给定索引处的任务。

array_splice() 函数会从数组中删除元素:

<?php
array_splice($array, $index, 1); // Removes 1 element at $index
?>

然后遍历剩余的任务,并按照之前相同的格式打印每个任务:

  • 如果任务已完成:- [task description] (Done)
  • 如果任务待处理:- [task description] (Pending)

每个任务单独打印一行。

示例:

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

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

如果输入依次为 Clean room、Read book、Exercise、Cook dinner、0 和 0,输出应为:

- Read book (Pending)
- Exercise (Pending)
- Cook dinner (Pending)

亲手试试

<?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));

// Read the index of the task to mark as complete
$completeIndex = (int)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];

// Mark the task at the specified index as complete
$todos[$completeIndex]["completed"] = true;

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

基础知识中的所有课

自己练习: PHP 在线编译器