3

我有一个简单的函数,它查看传入的 mySQL 数据类型,然后将其汇总到“类别”(在此代码中称为系列),以便我可以在类别级别应用默认值。无论如何,这段代码可以很好地查找整数、字符和文本类别,但在日期时间和小数类别上完全失败。我无计可施。任何帮助将不胜感激:

public static function get_family_type ( $col_type ) {
    $families = array (
                'integer' => array ( 'integer', 'int', 'tinyint', 'mediumint', 'bigint' ),
                'fixed' => array ( 'decimal', 'numeric' ),
                'floating' => array ( 'float' , 'double' ),
                'character' => array ( 'char', 'varchar' ),
                'datetime' => array ( 'datetime' , 'timestamp'),
                'time' => array ('time'),
                'date' => array ('year'),
                'text' => array ('tinytext', 'text', 'mediumtext' , 'longtext'),
                'blob' => array ('blob','tinyblob','mediumblob','longblob')
    );

    // first get rid of any optional length parameterisation
    list ( $col_type ) = explode ( "(" , $col_type , 2 );
    foreach ($families as $family => $family_members) {
        if ( array_search ( $col_type , $family_members , true ) ) {
            return $family;
        }
    }
    return "unknown $col_type";
}

注意最后一行的备份返回语句,然后查看我在代码中其他地方定义的表的输出。

    [18-Jun-2012 17:39:24] Getting default for family of integer
    [18-Jun-2012 17:39:24] Getting default for family of text
    [18-Jun-2012 17:39:24] Getting default for family of character
    [18-Jun-2012 17:39:24] Getting default for family of character
    [18-Jun-2012 17:39:24] Getting default for family of character
    [18-Jun-2012 17:39:24] Getting default for family of character
    [18-Jun-2012 17:39:24] Getting default for family of character
    [18-Jun-2012 17:39:24] Getting default for family of character
    [18-Jun-2012 17:39:24] Getting default for family of character
    [18-Jun-2012 17:39:24] Getting default for family of character
    [18-Jun-2012 17:39:24] Getting default for family of character
    [18-Jun-2012 17:39:24] Getting default for family of integer
    [18-Jun-2012 17:39:24] Getting default for family of integer
    [18-Jun-2012 17:39:24] Getting default for family of unknown decimal
    [18-Jun-2012 17:39:24] Getting default for family of character
    [18-Jun-2012 17:39:24] Getting default for family of unknown datetime
    [18-Jun-2012 17:39:24] Getting default for family of floating
4

2 回答 2

3

array_search成功时返回数组键,有时值为 0。在 php 中,0 强制为布尔值 false。你需要检查像

    if ( array_search ( $col_type , $family_members , true ) !== false ) {
        return $family;
    }

注意严格的比较!==

php 手册在 array_search 的文档中提到了这一点。

于 2012-06-18T18:12:31.890 回答
2

你的改变:

if ( array_search ( $col_type , $family_members , true ) ) {
            return $family;
    }

if ( in_array( $col_type , $family_members , true ) ) {
            return $family;
   }

注意:

array_search — 在数组中搜索给定的值,如果成功则返回相应的键

因此,它不是来自 array_search 的布尔返回,这可能是它无法按您希望的那样工作的原因。

于 2012-06-18T17:55:08.280 回答