按完成状态筛选
本课属于 Coddy PHP 学习旅程的“基础知识”单元。第 59 课,共 71 课。
挑战
简单在上一课中,你从列表中删除了一个任务。现在,添加按完成状态筛选任务的功能。
读取 4 行输入,获取任务描述(3 个初始任务加 1 个新任务)。然后读取第 5 个输入:一个整数,表示要标记为已完成的任务的索引。读取第 6 个输入:一个整数,表示要删除的任务的索引。最后,读取第 7 个输入:一个字符串,可以是 completed 或 pending,用于筛选任务。
构建 $todos 数组、将指定任务标记为已完成并删除给定索引处的任务后,根据筛选输入筛选剩余任务:
- 如果筛选值是
completed,只显示"completed"为true的任务 - 如果筛选值是
pending,只显示"completed"为false的任务
遍历剩余任务,只打印符合筛选条件的任务,并使用相同的格式:
- 如果任务已完成:
- [task description] (Done) - 如果任务未完成:
- [task description] (Pending)
将每个符合条件的任务打印在单独一行。
示例:
如果输入是 Buy groceries、Walk the dog、Finish homework、Call mom、1、2 和 completed,输出应为:
- Walk the dog (Done)如果输入是 Buy groceries、Walk the dog、Finish homework、Call mom、1、2 和 pending,输出应为:
- Buy groceries (Pending)
- Call mom (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));
// Read the index of the task to remove
$removeIndex = (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;
// Remove the task at the specified removal index
array_splice($todos, $removeIndex, 1);
// 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 在线编译器