vartec - 感谢您的帮助。你的想法给了我一个很好的起点。我进一步开发了它,扩展了 Zend_Db_Table,添加了一个从 MySQL 中吸取列元数据的函数,并使用它来设置默认值。我已经在下面发布了它的草稿。我还没有尝试简化它,并且只涵盖了我立即需要的字段类型。希望它可以帮助其他有同样问题的人。
public function reformatData($array) {
if (!is_array($array)) {
return false;
}
$cols = $this->info(Zend_Db_Table_Abstract::METADATA);
if (is_array($cols)) {
foreach ($cols as $col) {
if (array_key_exists($col['COLUMN_NAME'], $array)) {
switch ($col['DATA_TYPE']) {
case 'int': case 'tinyint':
if ($array[$col['COLUMN_NAME']] == '') {
$newArray[$col['COLUMN_NAME']] = new Zend_Db_Expr('null');
}
else {
$newArray[$col['COLUMN_NAME']] = $array[$col['COLUMN_NAME']];
}
break;
case 'date':
if ($array[$col['COLUMN_NAME']] == '') {
$newArray[$col['COLUMN_NAME']] = new Zend_Db_Expr('null');
}
elseif(!Zend_Date::isDate($array[$col['COLUMN_NAME']], 'YYYY-MM-dd')) {
$date = new Zend_Date($array[$col['COLUMN_NAME']], null, 'en_GB');
$newArray[$col['COLUMN_NAME']] = $date->toString('YYYY-MM-dd');
}
else {
$newArray[$col['COLUMN_NAME']] = $array[$col['COLUMN_NAME']];
}
break;
case 'datetime':
if ($array[$col['COLUMN_NAME']] == '') {
$newArray[$col['COLUMN_NAME']] = new Zend_Db_Expr('null');
}
elseif(!Zend_Date::isDate($array[$col['COLUMN_NAME']], 'YYYY-MM-dd HH:MM')) {
$date = new Zend_Date($array[$col['COLUMN_NAME']], null, 'en_GB');
$newArray[$col['COLUMN_NAME']] = $date->toString('YYYY-MM-dd HH:MM');
}
else {
$newArray[$col['COLUMN_NAME']] = $array[$col['COLUMN_NAME']];
}
break;
default:
$newArray[$col['COLUMN_NAME']] = $array[$col['COLUMN_NAME']];
break;
}
}
}
return $newArray;
}
else {
return false;
}
}