CapAm
CapAm

Reputation: 317

Retrieving data from DB in PHP using foreach

I have a sql to select all the row that matches with the user_id. Then I store that into an array using $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
        )
)

The problem is that using a foreach as this:

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

Only get:

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

And I would like to receive

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

How could I do to store both of then [0] and [1] into an array and then show them? I think the problem is in the foreach, and my goal is to save into a multidimensional array [][], where I can access using for example, $json_response[1][1] to the value of the second array (MM) and the second value.

Upvotes: 3

Views: 48

Answers (2)

Steve
Steve

Reputation: 20469

You are currently overwriting the values. Instead add them as seperate array elements:

//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];
}

This will produce the multidimentional array you mention in your last paragraph (not the comma separated values you show above it).

If you wanted the comma seperated values instead, you can implode the arrays after:

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

Upvotes: 1

Niranjan N Raju
Niranjan N Raju

Reputation: 11987

try like this,

$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,",");

Instead of looping it, you can get data directly in query from database. Something like this

GROUP_CONCAT(table_name.column_name SEPARATOR ', ')

and use GROUP BY.

Upvotes: 2

Related Questions