FluentUtils::convertToNativeTypes PHP Method

convertToNativeTypes() public static method

Converts columns from strings to types according to PDOStatement::columnMeta http://stackoverflow.com/a/9952703/3006989
public static convertToNativeTypes ( PDOStatement $statement, $rows ) : copy
$statement PDOStatement
return copy of $assoc with matching type fields
    public static function convertToNativeTypes(PDOStatement $statement, $rows)
    {
        for ($i = 0; $columnMeta = $statement->getColumnMeta($i); $i++) {
            $type = $columnMeta['native_type'];
            switch ($type) {
                case 'DECIMAL':
                case 'TINY':
                case 'SHORT':
                case 'LONG':
                case 'LONGLONG':
                case 'INT24':
                    if (isset($rows[$columnMeta['name']])) {
                        $rows[$columnMeta['name']] = $rows[$columnMeta['name']] + 0;
                    } else {
                        if (is_array($rows) || $rows instanceof Traversable) {
                            foreach ($rows as &$row) {
                                if (isset($row[$columnMeta['name']])) {
                                    $row[$columnMeta['name']] = $row[$columnMeta['name']] + 0;
                                }
                            }
                        }
                    }
                    break;
                case 'DATETIME':
                case 'DATE':
                case 'TIMESTAMP':
                    // convert to date type?
                    break;
                    // default: keep as string
            }
        }
        return $rows;
    }

Usage Example

示例#1
0
 /** Fetch all row
  *
  * @param string $index      specify index column
  * @param string $selectOnly select columns which could be fetched
  *
  * @return array of fetched rows
  */
 public function fetchAll($index = '', $selectOnly = '')
 {
     if ($selectOnly) {
         $this->select(null)->select($index . ', ' . $selectOnly);
     }
     if ($index) {
         $data = array();
         foreach ($this as $row) {
             if (is_object($row)) {
                 $data[$row->{$index}] = $row;
             } else {
                 $data[$row[$index]] = $row;
             }
         }
         return $data;
     } else {
         if (($s = $this->execute()) !== false) {
             if ($this->convertTypes) {
                 return FluentUtils::convertToNativeTypes($s, $s->fetchAll());
             } else {
                 return $s->fetchAll();
             }
         }
         return $s;
     }
 }