如何将Codeigniter DB返回字符串对象转换为int


How to convert Codeigniter DB return string object to int

    $sql = "SELECT catgy.category_id, catgy.category_title 
            FROM categories catgy
              INNER JOIN subj_category_relation scr
                ON scr.scr_id = catgy.category_id  
              INNER JOIN subjects subj
                ON subj.subject_id = '{$sId}'
            WHERE subj.subject_id = '{$sId}'
                AND subj.subject_id = scr.subject_id";
    $res = $this->db->query( $sql );
    if ($res) { 

        $results = $res->result_array();
        echo "<pre>";
        var_dump( $results );
        echo "</pre>"
        exit;       

vardump

array(5) {
  [0]=>
  array(2) {
    ["category_id"]=>
    string(1) "1"
    ["category_title"]=>
    string(5) "terms"
  }
  [1]=>
  array(2) {
    ["category_id"]=>
    string(1) "2"
    ["category_title"]=>
    string(6) "people"
  }
  [2]=>
  array(2) {
    ["category_id"]=>
    string(1) "3"
    ["category_title"]=>
    string(8) "places
"
  }
  [3]=>
  array(2) {
    ["category_id"]=>
    string(1) "4"
    ["category_title"]=>
    string(7) "works
"
  }
  [4]=>
  array(2) {
    ["category_id"]=>
    string(1) "5"
    ["category_title"]=>
    string(8) "events
"
  }
}

获取数据库int类型的字符串。正确的解决方案是什么?相反,转换每个数组可能不是一个好的解决方案。

数据库对象应该在对象中返回正确的值类型。PHP/MySQL旧版本存在问题。

https://dev.mysql.com/downloads/connector/php-mysqlnd/

安装php5-mysqlnd驱动程序

apt-get install php5-mysqlnd
service apache2 restart

参考:MySQL整数字段在PHP中作为字符串返回

检查@advait答案

$new_int_array = array();
foreach($results as $value){
    $new_int_array [] = array_map('intval', $value);
}
print_r($new_int_array); //this is new array with int type values.

尝试array_walk将string转换为int:

array_walk($results, function(&$a) {
    $a['category_id'] = (int)$a['category_id'];
});
var_dump($results);

演示

DB中检索偶数时,它被转换为字符串,因此您必须手动将它们转换回int