gmaran gmaran - 1 year ago 90
MySQL Question

Populate multimensional array in PHP

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

"key#1": 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;


I've got only one array for each key.

Answer Source

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;
$results[$key] = array();
$results[$key][] = $elements;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download