向JSON数组添加索引时数据表中断

时间:2015-04-04 01:42:38

标签: php jquery arrays json datatable

我有一个数据表,它从一个转换为JSON数组的php数组填充,当我只是从我的数据库中提取字段时,一切正常,但我想添加一些计算字段作为最后几列,所以我做了他们在PHP这里:

foreach ($in as $id){
    $query = $link->prepare("SELECT provider_num, provider_name, 233_net_charity_care, 291_cost_of_non_mcr_bad_debts, 301_cost_of_uncomp_care
                FROM `s10`
                            WHERE `id` = :id");
    $query->bindParam(':id', $id, PDO::PARAM_INT);
    $query->execute();
    $results = $query->fetch(PDO::FETCH_ASSOC);
    if($results['301_cost_of_uncomp_care'] != 0){
                $charityPortion = ($results['233_net_charity_care'] / $results['301_cost_of_uncomp_care']);
                $baddebtPortion = ($results['291_cost_of_non_mcr_bad_debts'] / $results['301_cost_of_uncomp_care']);
                } else {
                    $charityPortion = 0;
                    $baddebtPortion = 0;
                }
    $data[] = $results;
    /*$data['charityPortion'] = $charityPortion;
    $data['baddebtPortion'] = $baddebtPortion;*/
}

然后变成一个json变量,传递给datatables init var tableData = <?php echo json_encode($data); ?>;

然后用json初始化datable:

$('#compTab').dataTable({
        "aaData": tableData,                               
        "aoColumns": [
            { "data": "provider_num" },
            { "data": "provider_name" },
            { "data": "233_net_charity_care" },
            { "data": "291_cost_of_non_mcr_bad_debts" },
            { "data": "301_cost_of_uncomp_care" }
            /*{ "data": "charityPortion"},
            { "data": "baddebtPortion"}*/
        ]
    });

目前我将最后两列注释掉,因为每次将它们添加到我的数据数组时,datatables都会报告没有找到数据,即使在我回显JSON时值显示在正确的位置。

我的问题是:这两个变量是否缺少某些导致数据包跳闸的东西?我有一种感觉,我可能会以某种方式将它们作为对象传递,但我认为json_encode()

涵盖了它

对此的任何见解都会很棒。

提前致谢

1 个答案:

答案 0 :(得分:0)

为什么不直接在SQL字符串中计算charityPortion和baddebtPortion?然后,它将成为$ results的一部分:

SELECT  provider_num, provider_name, 233_net_charity_care, 
        291_cost_of_non_mcr_bad_debts, 301_cost_of_uncomp_care,
        if('301_cost_of_uncomp_care' != 0, 
            ('233_net_charity_care' / '301_cost_of_uncomp_care'), 0) As charityPortion,
        if('301_cost_of_uncomp_care' != 0, 
            ('291_cost_of_non_mcr_bad_debts' / '301_cost_of_uncomp_care'),0) As baddebtPortion
FROM `s10`
WHERE `id` = :id