处理空列表情况
本课属于 Coddy PHP 学习旅程的“基础知识”单元。第 60 课,共 71 课。
挑战
简单上一课中,你根据任务的完成状态筛选了任务。现在,添加对筛选结果为空的情况的处理。
读取 4 行输入作为任务描述(3 个初始任务和 1 个新任务)。然后读取第 5 个输入:一个整数,表示要标记为已完成的任务的索引。读取第 6 个输入:一个整数,表示要移除的任务的索引。最后,读取第 7 个输入:一个字符串,可以是 completed 或 pending,用于筛选任务。
创建 $todos 数组、将指定任务标记为已完成并移除给定索引处的任务后,根据筛选输入筛选剩余任务。
显示筛选后的任务前,检查是否有任务符合筛选条件:
- 如果没有任务符合筛选条件,输出:
No [filter] tasks found.(其中[filter]可以是completed或pending) - 如果有任务符合筛选条件,则使用与之前相同的格式显示它们
符合条件的任务的输出格式:
- 如果任务已完成:
- [task description] (Done) - 如果任务待处理:
- [task description] (Pending)
示例 1:
如果输入依次为 Buy groceries、Walk the dog、Finish homework、Call mom、1、1 和 completed,输出应为:
No completed tasks found.示例 2:
如果输入依次为 Buy groceries、Walk the dog、Finish homework、Call mom、0、2 和 completed,输出应为:
- Buy groceries (Done)示例 3:
如果输入依次为 Buy groceries、Walk the dog、Finish homework、Call mom、0、1 和 pending,输出应为:
- Finish homework (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));
// Read the filter type (completed or pending)
$filter = 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 that matches the filter
foreach ($todos as $todo) {
if ($filter === "completed" && $todo["completed"]) {
echo "- " . $todo["task"] . " (Done)\n";
} elseif ($filter === "pending" && !$todo["completed"]) {
echo "- " . $todo["task"] . " (Pending)\n";
}
}
?>基础知识中的所有课
自己练习: PHP 在线编译器