You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DataTables中Integer类型的status列转为对应字符串显示?

问题描述

数据库projects表中的projectStatus列存储0、1、2这类整数,当前通过DataTables展示数据时直接显示数字,需要将其转换为对应字符串:

  • 0 → 待处理
  • 1 → 运行中
  • 2 → 已完成

当前使用的PHP代码如下:

// DB table to use 
$table = 'projects';

// Table's primary key 
$primaryKey = 'projectID';

// Array of database columns which should be read and sent back to DataTables. 
// The `db` parameter represents the column name in the database.  
// The `dt` parameter represents the DataTables column identifier. 
$columns = array(
    array('db' => 'projectName', 'dt' => 0),
    array('db' => 'projectDescription',  'dt' => 1),
    array('db' => 'destinationName',      'dt' => 2),
    array('db' => 'projectStatus',     'dt' => 3), // 这里是状态列
    array('db' => 'startDate',    'dt' => 4),
    array('db' => 'endDate',    'dt' => 5)
);

// Include SQL query processing class 
require 'ssp.class.php';

// Output data as json format 
echo json_encode(
    SSP::simple($_GET, $dbDetails, $table, $primaryKey, $columns)
);

需求逻辑:

  • 当projectStatus为0时显示"待处理"
  • 当projectStatus为1时显示"运行中"
  • 当projectStatus为2时显示"已完成"
解决方案

有两种常用实现方式,可根据需求选择:

方法一:后端PHP处理(推荐)

利用SSP类支持的formatter回调函数,在返回JSON前完成状态转换,修改columns数组中projectStatus的配置:

$columns = array(
    array('db' => 'projectName', 'dt' => 0),
    array('db' => 'projectDescription',  'dt' => 1),
    array('db' => 'destinationName',      'dt' => 2),
    array(
        'db' => 'projectStatus', 
        'dt' => 3,
        // 自定义格式化函数
        'formatter' => function($value, $row) {
            $statusMap = [
                0 => '待处理',
                1 => '运行中',
                2 => '已完成'
            ];
            // 若存在匹配状态则返回对应字符串,否则返回原数值
            return isset($statusMap[$value]) ? $statusMap[$value] : $value;
        }
    ),
    array('db' => 'startDate',    'dt' => 4),
    array('db' => 'endDate',    'dt' => 5)
);

此方法的优势是前端无需额外处理,直接渲染转换后的文本。

方法二:前端DataTables处理

如果不想修改后端逻辑,可在DataTables初始化时通过columnDefs的render函数实现转换:

$(document).ready(function() {
    $('#your-table-id').DataTable({
        // 其他配置项...
        columnDefs: [
            {
                targets: 3, // 对应后端dt=3的列索引
                render: function(data, type, row) {
                    const statusMap = {
                        0: '待处理',
                        1: '运行中',
                        2: '已完成'
                    };
                    return statusMap[data] || data;
                }
            }
        ]
    });
});

此方法适合需保留后端原始数据,仅前端展示转换文本的场景。

内容的提问来源于stack exchange,提问作者Lee Huat Chong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 12:30:52