gpt4 book ai didi

php - array_search 行为不可预测

转载 作者:可可西里 更新时间:2023-11-01 00:49:12 26 4
gpt4 key购买 nike

我有一个简单的函数,它查看传入的 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

最佳答案

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

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

注意严格比较 !==

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

关于php - array_search 行为不可预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11088259/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com