I have a simple function that looks at an incoming mySQL data type and then rolls it up to a "category" (called a family in this code) so that I can apply default values at the category level. Anyway, this code works fine for finding integer, character, and text categories but completely fails on datetime and decimal categories. I'm at my wits end. Any help would be greatly appreciated:
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";
}
note the backup return statement on the last line and then look at this output from a table I've defined elsewhere in code.
[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 returns the array key on success, and that will sometimes be the value of 0. In php, 0 coerces to boolean false. You need to check like
if ( array_search ( $col_type , $family_members , true ) !== false ) {
return $family;
}
Note the strict comparsion !==
the php manual mentions this in the documentation for array_search.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With