CI 获取数据库数据类型总是为STRING 的解决方案

This isn’t something I have time to do today, but for anyone else who comes across this problem, you can probably enable json_encodeto output numbers from active records with the following steps:

1) Modify the mysql/mysql_resultphp file to include the$field->numeric metadata attribute.
2) Add an extra step to active record queries that uses CodeIgniter’s $this->db->field_data() totest for any fields with numeric==1
3) If numeric==1, cast that field’s value to a number.

function field_data()
    
{
        $retval 
= array();
        while (
$field mysql_fetch_field($this->result_id))
        
{    
            $F                
= new stdClass();
            
$F->name         $field->name;
            
$F->type         $field->type;
            
$F->default        $field->def;
            
$F->max_length    $field->max_length;
            
$F->primary_key $field->primary_key;
                        
$F->numeric $field->numeric// <!-- ADD THIS LINE
            
            
$retval[] $F;
        
}
        
        
return $retval;
    

Heavy reliance on JSON in my scenario might make the extra effortworthwhile, but most people might never run into this.

2、It’s a blunt wayto solve the problem, but “good enough” for me. The functioncomments are based on PHP’s settype() documentationat http://us2.php.net/manual/en/function.settype.php

<?php

function cast_fieldtypes($record$fieldTypes{
    
foreach($record as $fieldName => $value{
        
if(isset($fieldTypes[$fieldName])) {
            $type 
$fieldTypes[$fieldName];
            
$value $record[$fieldName];
            switch (
$type{
                
case 'boolean':
                case 
'bool':
                    
$value = (bool) $value;
                    break;
                
                case 
'integer':
                case 
'int':
                    
$value = (int) $value;
                    break;

                case 
'float':
                    
$value = (float) $value;
                    break;
                    
                case 
'string':
                    
$value = (string) $value;
                    break;

                default:
                    break;
            
}
            $record[$fieldName] 
$value;
        
}
    }
    
return $record;
}
?> 

Here’s an exampleof how to use it:

// Declare the types for some of the fields (not necessarily all of them)
$fieldTypes = array(
    
'weight'=>'int',
    
'revision'=>'int',
    
'is_visible'=>'bool',
);
$record $this->db->get_where('content', array('id'=>1));
$casted_record cast_fieldtypes($record$fieldTypes);
echo 
json_encode($casted_record); 
 
展开阅读全文
©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值