Last active
August 16, 2019 12:01
-
-
Save AeonFr/db3b2a8a95753076d9e4da42d29365d2 to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: Tested in PHP 5.6 and MySQL 15.0 (10.0 MariaDB)