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

时间:2014-03-27 15:05:09

标签: php codeigniter

    $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
"
  }
}

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

3 个答案:

答案 0 :(得分:0)

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

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

安装php5-mysqlnd驱动程序

apt-get install php5-mysqlnd
service apache2 restart

参考: MySQL integer field is returned as string in PHP

Check @advait answer

答案 1 :(得分:-1)

尝试array_walkstring转换为int

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

var_dump($results);

DEMO

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

答案 2 :(得分:-1)

$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.