简体   繁体   中英

Access key values within an associative array in PHP

I am having trouble with associative arrays and sql queries. The thing is I have a query which has its lines stored into an array like this:

$query21 = "SELECT PROCESSO, DATAMSG, CATEGORIA_DESC, VALOR, CRITICO FROM TABLEX";
$result21 = oci_parse($connect, $query21);
oci_execute($result21);

$c1=array();
while($res21 = oci_fetch_array($result21))  {
    $c1[]=$res21;
}
print_r($c1);

This code prints this:

Array
(
    [0] => Array
        (
            [0] => 1647306
            [PROCESSO] => 1647306
            [1] => 2015-04-27 23
            [DATAMSG] => 2015-04-27 23
            [2] => ECG_HR                        
            [CATEGORIA_DESC] => ECG_HR                        
            [3] => 59
            [VALOR] => 59
            [4] => 1
            [CRITICO] => 1
       )
)

The problem is I don't know why it is repeating the results twice. I expected the result like this:

Array
(
    [0] => Array
        (
            [PROCESSO] => 1647306
            [DATAMSG] => 2015-04-27 23                       
            [CATEGORIA_DESC] => ECG_HR                        
            [VALOR] => 59
            [CRITICO] => 1
       )
)

Also how can I access the [PROCESSO] ,..., [CRITICO] key values? I have tried but can only access the $c1['0'] key which holds the array, though I need the values inside.

Because by default oci_fetch_array() uses OCI_BOTH fetching mode; that means it returns an array with both associative and numeric indices. You may either explicitly switch numeric indexing off with...

oci_fetch_array($result21, OCI_ASSOC)

... or just use oci_fetch_assoc() instead.

You might also consider dropping while altogether and just using oci_fetch_all() in fill-by-row mode:

oci_fetch_all($result21, $c1, null, null, OCI_FETCHSTATEMENT_BY_ROW);

In either case, you'll be able to iterate over those arrays with the same techniques you iterate over any other one. For example:

foreach ($c1 as $row) {
  foreach ($row as $key => $value) {
    echo $key, ' is ', $value, '<br />';
  }
}

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