php - 在 codeigniter 中获取 tinyint 的查询结果列值作为 true/false

标签 php mysql json codeigniter

我在 my_table 中有一列,其数据类型为 tinyint
a column of table contains tinyint datatype

CodeIgniter 模型类:

public function get_all() {
    $query = $this->db->get('my_table');
    return $query->result();
}

查询结果返回 is_active 字段的值作为字符串“0”/“1”。我希望它是真/假。因此,该字段的 json 数据是真/假。
Controller 类:

$query_result = $this->model->get_all();
echo json_encode($query_result);

我怎么得到这个?

更新: 查询结果数组为:

Array (
[0] => stdClass Object
    (
        [brand_id] => 1014
        [brand_name] => Coca Cola
        [brand_logo] => coca_cola_logo2.png
        [is_active] => 1
    )

[1] => stdClass Object
    (
        [brand_id] => 1015
        [brand_name] => Hallmark
        [brand_logo] => hallmark_logo.jpg
        [is_active] => 0
    )

[2] => stdClass Object
    (
        [brand_id] => 1016
        [brand_name] => Binjar
        [brand_logo] => binjar3.png
        [is_active] => 1
    )

)

最佳答案

答案是不需要转换。

但如果你坚持...

在 PHP 方面,除了使用 array_map() 之外,您还可以遍历结果集并将值转换为 bool 值。

foreach($query_result as $result){
  $result->is_active = (bool) $result->is_active;
}

就这么简单……但毫无意义。整数 1 和 0 将使用松散比较评估为 TRUE 和 FALSE,例如。

var_dump(1 == TRUE);
var_dump(0 == TRUE);

会输出

boolean true

boolean false

Javascript 还能够测试返回数据的“真实性”,无论返回值是 true"1" 还是整数 1.

这里有一个 Controller 和 View 来测试前提。

Controller :

<?php

class Testcase extends CI_Controller
{
  function __construct()
  {
    parent::__construct();
    $this->load->helper('form');
  }

  function index()
  {
    $this->load->view('test_view');
  }

  public function respond()
  {
    $data = array('asString' => '1', 'asBool' => TRUE, 'asInt' => 1);
    echo json_encode($data);
  }

}

查看:

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  </head>
  <body>
    <?= form_open("#", ['id' => 'form']); ?>
    <input type="submit" id="btn" value="Click Me!">
    <?= form_close(); ?>
    <div id="as-string"></div>
    <div id="as-bool"></div>
    <div id="as-int"></div>

    <script>
      $(document).ready(function () {
        $("#form").submit(function (event) {
          event.preventDefault();
          $.ajax({
            type: 'POST',
            url: 'testcase/respond',
            data: $('#form').serializeArray(),
            dataType: "json",
            success: function (data) {
              console.log(data);
              if (data.asString == true) {
                $('#as-string').text('String returned is True');
              } else {
                $('#as-string').text('String returned is False');
              }
              if (data.asBool == true) {
                $('#as-bool').text('Boolean returned is True');
              } else {
                $('#as-bool').text('Boolean returned is False');
              }
              if (data.asInt == true) {
                $('#as-int').text('Integer returned is True');
              } else {
                $('#as-int').text('Integer returned is False');
              }
            }
          });
        });
      });
    </script>
  </body>
</html>

提交表单在浏览器中产生这个结果

String returned is True

Boolean returned is True

Integer returned is True

像这样将返回更改为 FALSE 的各种表示形式,

$data = array('asString' => '0', 'asBool' => FALSE, 'asInt' => 0);
echo json_encode($data);

然后点击按钮产生

String returned is False

Boolean returned is False

Integer returned is False

请注意,javascript 使用松散相等 (==) 进行条件检查。如果更改为严格相等 (===),结果会发生变化。

更改成功函数以使用严格相等...

success: function (data) {
  console.log(data);
  if (data.asString === true) {
    $('#as-string').text('String returned is True');
  } else {
    $('#as-string').text('String returned is False');
  }
  if (data.asBool === true) {
    $('#as-bool').text('Boolean returned is True');
  } else {
    $('#as-bool').text('Boolean returned is False');
  }
  if (data.asInt === true) {
    $('#as-int').text('Integer returned is True');
  } else {
    $('#as-int').text('Integer returned is False');
  }
}

并从 Controller 返回这些数据

$data = array('asString' => '1', 'asBool' => TRUE, 'asInt' => 1);

产生这个结果

String returned is False

Boolean returned is True

Integer returned is False

使用“虚假”数据...

$data = array('asString' => '0', 'asBool' => FALSE, 'asInt' => 0);

结果是这样的

String returned is False

Boolean returned is False

Integer returned is False

因此,通过使用松散相等 (==),您可以进行条件测试,而不必担心 Controller 返回的数据类型。

关于php - 在 codeigniter 中获取 tinyint 的查询结果列值作为 true/false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37507968/

相关文章:

PHPExcel:将 Excel 插入 SQL 数据库时单元格坐标 A 无效

PHP 从 mysql 返回一个结果,但是如果我 while 循环结果,什么也没有显示

php - 使用 PHP 和 JavaScript 动态更新 Google Chart

php - 在 MySQL 数据库中搜索相关/包含多个标签记录的书签

ios - 使用 swiftyJSON 和 sqlite.swift 将基于 json 的数据添加到 sqlite 数据库中

php - 带有订阅的 Stripe 付款请求按钮

php - 如何简化我的国家选择菜单 PHP/mysql

php - 我无法在循环之外获取查询的值

python - 如何从 Modbus Slave 读取所有保持寄存器?

php - 处理 JSON 格式的 POST 请求