4E e 4I: Gli array nidificati in Php con il modulo form, inserimento e stampa

Registro Valutazioni Studenti

Realizza una pagina PHP contenente un modulo HTML per registrare uno studente con i suoi dettagli anagrafici e i voti ottenuti in tre materie (Matematica, Italiano, Inglese).

I dati inseriti devono essere salvati in una variabile di sessione organizzata come array multidimensionale (nidificato) e successivamente stampati a schermo tramite cicli foreach nidificati, calcolando anche la media dei voti per ciascuno studente.


Codice Sorgente Completo (index.php)


PHP

<?php
session_start();

// Inizializza l'array degli studenti in sessione se non esiste
if (!isset($_SESSION['studenti'])) {
    $_SESSION['studenti'] = [];
}

// Gestione del reset dei dati
if (isset($_POST['reset'])) {
    $_SESSION['studenti'] = [];
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Gestione dell'inserimento dati tramite FORM
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['inserisci'])) {
    $nome = trim($_POST['nome'] ?? '');
    $cognome = trim($_POST['cognome'] ?? '');
    $matematica = filter_input(INPUT_POST, 'matematica', FILTER_VALIDATE_FLOAT);
    $italiano = filter_input(INPUT_POST, 'italiano', FILTER_VALIDATE_FLOAT);
    $inglese = filter_input(INPUT_POST, 'inglese', FILTER_VALIDATE_FLOAT);

    if (!empty($nome) && !empty($cognome) && $matematica !== false && $italiano !== false && $inglese !== false) {
       
        // Creazione della struttura dell'ARRAY NIDIFICATO
        $nuovoStudente = [
            'anagrafica' => [
                'nome' => $nome,
                'cognome' => $cognome
            ],
            'voti' => [
                'Matematica' => $matematica,
                'Italiano'   => $italiano,
                'Inglese'    => $inglese
            ]
        ];

        // Inserimento del sotto-array nell'array principale
        $_SESSION['studenti'][] = $nuovoStudente;
    }
}
?>

<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="UTF-8">
    <title>Esercizio Array Nidificati PHP</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; }
        .form-container, .output-container { background: #f4f4f4; padding: 20px; margin-bottom: 20px; border-radius: 8px; }
        .field { margin-bottom: 10px; }
        label { display: inline-block; width: 100px; font-weight: bold; }
        input[type="text"], input[type="number"] { padding: 5px; width: 200px; }
        .btn { padding: 8px 15px; background: #28a745; color: white; border: none; cursor: pointer; border-radius: 4px; }
        .btn-reset { background: #dc3545; }
        table { width: 100%; border-collapse: collapse; margin-top: 10px; background: white; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #007bff; color: white; }
    </style>
</head>
<body>

    <h2>Registro Studenti (Array Nidificati in PHP)</h2>

    <!-- FORM INSERIMENTO -->
    <div class="form-container">
        <h3>Inserisci Nuovo Studente</h3>
        <form action="" method="POST">
            <div class="field">
                <label for="nome">Nome:</label>
                <input type="text" id="nome" name="nome" required>
            </div>
            <div class="field">
                <label for="cognome">Cognome:</label>
                <input type="text" id="cognome" name="cognome" required>
            </div>
            <div class="field">
                <label for="matematica">Matematica:</label>
                <input type="number" id="matematica" name="matematica" min="2" max="10" step="0.5" required>
            </div>
            <div class="field">
                <label for="italiano">Italiano:</label>
                <input type="number" id="italiano" name="italiano" min="2" max="10" step="0.5" required>
            </div>
            <div class="field">
                <label for="inglese">Inglese:</label>
                <input type="number" id="inglese" name="inglese" min="2" max="10" step="0.5" required>
            </div>
            <button type="submit" name="inserisci" class="btn">Aggiungi Studente</button>
            <button type="submit" name="reset" class="btn btn-reset">Svuota Registro</button>
        </form>
    </div>

    <!-- STAMPA DEI DATI -->
    <div class="output-container">
        <h3>Elenco Studenti e Voti</h3>

        <?php if (empty($_SESSION['studenti'])): ?>
            <p>Nessun studente presente nel registro.</p>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Nome Completo</th>
                        <th>Voti per Materia</th>
                        <th>Media Voti</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // Primo livello di iterazione: scorre l'array principale (studenti)
                    foreach ($_SESSION['studenti'] as $indice => $studente):
                        $sommatoriaVoti = 0;
                        $numeroMaterie = count($studente['voti']);
                    ?>
                        <tr>
                            <td><?= $indice + 1 ?></td>
                            <td>
                                <!-- Accesso ai sotto-elementi dell'array "anagrafica" -->
                                <strong><?= htmlspecialchars($studente['anagrafica']['cognome']) ?></strong>
                                <?= htmlspecialchars($studente['anagrafica']['nome']) ?>
                            </td>
                            <td>
                                <ul>
                                    <?php
                                    // Secondo livello di iterazione: scorre il sotto-array associativo (voti)
                                    foreach ($studente['voti'] as $materia => $voto):
                                        $sommatoriaVoti += $voto;
                                    ?>
                                        <li><strong><?= $materia ?>:</strong> <?= number_format($voto, 1) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </td>
                            <td>
                                <?php
                                $media = $sommatoriaVoti / $numeroMaterie;
                                echo "<strong>" . number_format($media, 2) . "</strong>";
                                ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

</body>
</html>


Struttura dell'Array Nidificato Creato

L'array memorizzato in $_SESSION['studenti'] assume la seguente struttura multidimensionale:



PHP

Array (
    [0] => Array (
        [anagrafica] => Array (
            [nome] => Mario
            [cognome] => Rossi
        )
        [voti] => Array (
            [Matematica] => 8.0
            [Italiano] => 7.5
            [Inglese] => 6.0
        )
    )
    [1] => Array (
        [anagrafica] => Array (
            [nome] => Laura
            [cognome] => Bianchi
        )
        [voti] => Array (
            [Matematica] => 9.0
            [Italiano] => 8.5
            [Inglese] => 9.5
        )
    )
)


Come Funziona l'Esercizio

Gestione dello Stato ($_SESSION): Utilizziamo le sessioni PHP per mantenere memorizzati gli studenti tra una richiesta HTTP e l'altra, simulando un database temporaneo.


Costruzione dell'Array Multidimensionale:

$_SESSION['studenti'] è l'array contenitore principale (indicizzato numericamente).

Ogni elemento è un array associativo con due chiavi principali: 'anagrafica' e 'voti'.

'anagrafica' è a sua volta un array associativo (chiavi nome e cognome).

'voti' è un sub-array associativo contenente le materie come chiavi e i rispettivi punteggi come valori.

Lettura con Cicli Nidificati:

Il primo foreach scorre la lista degli studenti: foreach ($_SESSION['studenti'] as $studente).

L'accesso diretto avviene tramite sintassi a doppi apici: $studente['anagrafica']['nome'].

Il secondo foreach legge le coppie chiave-valore all'interno dell'array delle materie: foreach ($studente['voti'] as $materia => $voto).

Commenti

Post popolari in questo blog

Esercizi in Excel e fogli di Google

Simulazioni di reti (con Cisco Packet Tracer)