Menu
Coddy logo textTech

Filtrare per stato di completamento

Fa parte della sezione Fondamenti del percorso PHP di Coddy. Lezione 59 di 71.

challenge icon

Sfida

Facile

Nella lezione precedente, hai rimosso un'attività dall'elenco. Ora aggiungi la possibilità di filtrare le attività in base al loro stato di completamento.

Leggi quattro righe di input per le descrizioni delle attività (tre attività iniziali più una nuova attività). Poi leggi un quinto input: un numero intero che rappresenta l'indice dell'attività da contrassegnare come completata. Leggi un sesto input: un numero intero che rappresenta l'indice dell'attività da rimuovere. Infine, leggi un settimo input: una stringa che può essere completed oppure pending, da usare per filtrare le attività.

Dopo aver creato l'array $todos, contrassegnato come completata l'attività specificata e rimosso l'attività all'indice indicato, filtra le attività rimanenti in base all'input del filtro:

  • Se il filtro è completed, mostra solo le attività per cui "completed" è true
  • Se il filtro è pending, mostra solo le attività per cui "completed" è false

Scorri le attività rimanenti e stampa solo quelle che corrispondono al filtro, usando lo stesso formato:

  • Se l'attività è completata: - [task description] (Done)
  • Se l'attività è in sospeso: - [task description] (Pending)

Stampa ogni attività corrispondente su una riga separata.

Esempio:

Se gli input sono Buy groceries, Walk the dog, Finish homework, Call mom, 1, 2 e completed, l'output dovrebbe essere:

- Walk the dog (Done)

Se gli input sono Buy groceries, Walk the dog, Finish homework, Call mom, 1, 2 e pending, l'output dovrebbe essere:

- Buy groceries (Pending)
- Call mom (Pending)

Provalo tu

<?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";
    }
}
?>

Tutte le lezioni di Fondamenti

Esercitati da solo: Compilatore PHP online