【问题标题】:Populate multi dimensional array in PHP在 PHP 中填充多维数组
【发布时间】:2017-01-25 18:51:56
【问题描述】:

您好,我的 MySQL 数据库中有一些记录。我必须像这样填充一个多维关联数组:

results{
    "key#1": array
             array 
             array
    "key#2": 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);

每个键只有一个数组。

【问题讨论】:

    标签: php mysql arrays multidimensional-array key-value


    【解决方案1】:

    如果$key 不存在于$result 中,则每次使用make $results[$key] 作为数组时,您将覆盖值$results[$key],否则在$results[$key] 上附加$elements

    $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;
    }
    

    【讨论】:

    • 谢谢,我完全错过了这个。 :-)
    猜你喜欢
    • 1970-01-01
    • 2012-11-20
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    相关资源
    最近更新 更多