看标题大家可能云里雾里,这里解释下:就是一个页面有一个表格(分页的),表格上面有一行,是对表格金额字段的汇总(所有数据汇总,不是汇总当前页),但是这个金额的类型是不固定的(从配置读取),未来还会增加金额类型。
查看Layui版本:alert(layui.v);
Layui
表格加载完成done
之后给对应的金额类型赋值对应的值money_1,money_2,...,money_n
,则PHP代码如下:public function test(){
//比如配置的值如下
$config = [
['name' => '金额1', 'value' => 1],
['name' => '金额2', 'value' => 2],
['name' => '金额3', 'value' => 3],
];
//初始化动态的金额类型的值
//这里相当于: $money1 = $money2 = $money3 = 0;
foreach ($config as $k => $v){
$moneyName = 'money' . $v['value'];
$$moneyName = 0;
}
//echo $money1; //输出 0
$moneyData = [1 => 10, 2 => 20, 3 => 30]; //假设这是查询出来moneyData的值,moneyData可能为空
//当金额类型的值存在时,重置$money1,$money2,$money3的值
if ($moneyData){
foreach ($moneyData as $k => $v){
$moneyName = 'money' . $k;
$$moneyName = $v;
}
}
//echo $money1; //该值已被重置,打印 10
// $result为返回的值
$result = [
'id' => 1,
'name' => '金额类型',
'other_money' => 999,
];
//动态拼接金额类型$money1,$money2,$money3的值
foreach ($config as $k => $v){
$moneyName = 'money' . $v['value'];
$result = array_merge($result, ['money_' . $k => $$moneyName]);
}
var_export($result);
}
array (
'id' => 1,
'name' => '金额类型',
'other_money' => 999,
'money_0' => 10,
'money_1' => 20,
'money_2' => 30,
)
public function test(){
//比如配置的值如下
$config = [
['name' => '金额1', 'value' => 1],
['name' => '金额2', 'value' => 2],
['name' => '金额3', 'value' => 3],
];
$result = []; //注意:我们这里只用到了$result中的id,title字段;field字段是在动态渲染表格列中用到了
$config = array_column($config, 'name', 'value');
foreach ($config as $k => $v){
$moneyName = 'money_' . $k;
$result[] = [
'id' => $k,
'field' => $moneyName,
'title'=> $v
];
}
var_export($result);
}
array (
0 =>
array (
'id' => 1,
'field' => 'money_1',
'title' => '金额1',
),
1 =>
array (
'id' => 2,
'field' => 'money_2',
'title' => '金额2',
),
2 =>
array (
'id' => 3,
'field' => 'money_3',
'title' => '金额3',
),
)
$this->assign('result', $result);
其他费用:<span class="money-class" id="other-money">span>
{foreach $result as $key=>$value}
{$value.title}:<span class="money-class" id="money-{$value.id}">span>
{/foreach}
done
之后给动态的金额类型赋值//获取PHP传过来的$result
let result = {:json_encode($result)};
//表格渲染完成之后动态赋值
//表格渲染
let tableObject = table.render({
elem: '#id'
,url: 'url'
,cols: [cols]
,text: {
none: '暂无数据'
}
//...
,done:function(res, curr, count){
if(curr == 1){ //如果是第一页才重新计算总和
$.ajax({
type: "POST",
url: "/.../test",
data: globalWhere,
dataType: "json",
success: function (res) {
$('span#other-money').text(res.data.other_money);
//动态赋值
let length = result.length;
for (let i = 0; i < length; i++){
let key = 'money_' + result[i]['id']; //后台传过来的汇总值
$('span#money-'+result[i]['id']).text(res.data[key]);
}
}
});
}
}
});