Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
From a PDO Statement, fetch all the results and store them in an associative array, mapping integer and float values to PHP int and float types. It reads the column metadata to read the value's type.
<?php
// Returns the contents of $stm (PDO Statement)
// as an associative array, with correct native types
// for integers, nulls, and floats
$array = [];
while ($fila = $stm->fetch(\PDO::FETCH_ASSOC)) {
$i = 0;
$columnMetas = [];
while ($columnMeta = $stm->getColumnMeta($i)) {
$columnMetas[$columnMeta['name']] = $columnMeta;
$i++;
}
foreach ($fila as $key => $value) {
if ($value === null) {
continue;
}
$columnMeta = $columnMetas[$key];
switch ($columnMeta['native_type']) {
case 'LONG':
case 'TINY':
$fila[$key] = intval($value);
break;
case 'DOUBLE':
$fila[$key] = floatval($value);
break;
}
$i++;
}
$array[] = $fila;
}
return $array;
?>
@AeonFr

This comment has been minimized.

Copy link
Owner Author

commented Aug 16, 2019

Note: Tested in PHP 5.6 and MySQL 15.0 (10.0 MariaDB)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.