简体   繁体   中英

Populate multi dimensional array in PHP

Hi there I've got some records from my MySQL DB. I have got to populate a multi dimensional associative array like so:

results{
    "key#1": array
             array 
             array
    "key#2": array
             ...
}

I use the following code to create my data structure but I don't know exactly how to push data in my associative multidimensional array.

while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    $nome_paziente = $row[0];
    $numero_richiesta = $row[1];
    $importo_manuale = $row[2];
    $sconto_totale = $row[3] + $row[4];
    $importo_finale = round(($row[5] - (($row[5] * $sconto_totale)/100)),2);
    $id_centro_operativo = $row[7];
    $descrizione = $row[9];
    $codice_convenzione = $row[10];

    $elements = array(
        'nome_paziente' => $nome_paziente,
        'numero_richiesta' => $numero_richiesta,
        'importo_manuale' => $importo_manuale,
        'importo_finale' => $importo_finale,
        'descrizione' => $descrizione,
        'codice_convenzione' => $codice_convenzione
    );

    $key = $row[8]."#sep#".$row[6]; //nome_studio#data_appuntamento
    $results[$key] = $elements;
}

var_dump($results);

I've got only one array for each key.

you are overriding value $results[$key] every time use make $results[$key] as a array if $key doesn't exist in $result else append $elements on $results[$key]

$key = $row[8]."#sep#".$row[6]; //nome_studio#data_appuntamento
if (array_key_exists($key,$results)) {
 $results[$key][] = $elements;
}
else{
$results[$key] = array();
$results[$key][] = $elements;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM