使用foreach从PHP中的DB中检索数据

时间:2015-11-26 16:36:57

标签: php arrays foreach

我有一个sql来选择与user_id匹配的所有行。然后我使用$dataFromDB = $stmtA->fetchAll();

将其存储到数组中
Array
(
    [0] => Array
        (
            [0] => 55
            [1] => 7
            [2] => temperature
            [3] => 1
            [4] => 19
            [5] => 35
            [6] => 2015-11-26 14:41:34
        )
    [1] => Array
        (
            [0] => 56
            [1] => 7
            [2] => humidity
            [3] => 1
            [4] => 37
            [5] => 57
            [6] => 2015-11-26 14:42:36
        )
)

问题在于使用foreach:

foreach( $dataFromDB as $k => $row ){
    $json_response['SS'] = $row[2];
    $json_response['MN'] = $row[4];
    $json_response['MX'] = $row[5];
}

只得到:

[SS] => humidity
[MM] => 37
[MX] => 57

我想收到

[SS] => temperature, humidity
[MM] => 19, 37
[MX] => 35, 57

如何将[0]和[1]存储到数组中然后显示它们?我认为问题出在foreach中,我的目标是保存到多维数组[] [],我可以使用例如$ json_response [1] [1]访问第二个数组(MM)的值和第二个值。

2 个答案:

答案 0 :(得分:2)

尝试这样,

$ss = $mn = $mx = "";
foreach( $dataFromDB as $k => $row ){
    $ss .= $row[2];
    $mn .= $row[4];
    $mx .= $row[5];
}

$json_response['SS'] = rtrim($ss,",");
$json_response['MN'] = rtrim($mn,",");
$json_response['MX'] = rtrim($mx,",");

您可以直接从数据库中查询数据,而不是循环它。 像这样的东西

GROUP_CONCAT(table_name.column_name SEPARATOR ', ')

并使用GROUP BY

答案 1 :(得分:1)

您目前正在覆盖这些值。而是将它们添加为单独的数组元素:

//initialize with empty arrays
$json_response=['SS'=>[], 'MN'=>[], 'MX'=>[]];

foreach( $dataFromDB as $k => $row ){
    $json_response['SS'][] = $row[2];
    $json_response['MN'][] = $row[4];
    $json_response['MX'][] = $row[5];
}

这将生成您在上一段中提到的多维数组(不是您在其上方显示的逗号分隔值)。

如果您想要逗号分隔值,则可以在以下内容之后内爆数组:

foreach($json_response as &$val)
    $val = implode(',', $val);