gpt4 book ai didi

php - 数据表按数字字段排序

转载 作者:行者123 更新时间:2023-12-01 04:22:31 25 4
gpt4 key购买 nike

我的 DataTable Grid 中有一个代表金钱值的列,我如何正确排序这些值,因为 dataTable 仅按第一个数字排序,例如:

9.000,00

8.000,00

5.454.043,00

4.454.043,00

当然应该是这样的:

5.454.043,00

4.454.043,00

9.000,00

8.000,00

我正在使用number_format设置我的货币格式。

php:

<td>".number_format($money,2,',','.')."</td>

有任何问题,请成为我的客人。

谢谢。

<小时/>

编辑:

作为@Mikhail的回答,尝试这个,但是位置3的列不要再排序。

 ...
"aoColumnDefs": [
{ "sType": "numeric", "aTargets": [ 3 ] }
],
...
<小时/>

编辑2

更多代码:

php:

while(!$res->EOF){
... // post only the 3 <td> position
<td style='text-align: right;'>".number_format($value,2,',','.')."</td>
...
$res->MoveNext();
}

js数据表

var oTable = $('#example').dataTable({
"bJQueryUI": true,
"sScrollY": "225px",
"sScrollX": "100%",
"sScrollXInner": "100%",
"bDestroy" : true,
"bScrollCollapse": true,
"aoColumnDefs": [
{ "sType": "numeric", "aTargets": [ 3 ] }
],
"sDom": '<"H"Tfr>t<"F"ip>',
"oTableTools": {
"sSwfPath": "js/DataTables/extras/TableTools/media/swf/copy_cvs_xls_pdf.swf",
"sRowSelect": "single",
"aButtons": [
{
"sExtends": "xls",
"sButtonText": "Excel"
},
{
"sExtends": "print",
"sButtonText": "Print"
}
]
},
"aaSorting": [[ 0, "asc" ]],
"bPaginate": false
});
<小时/>

解决方案

我的解决方案是创建一个新列,其值不带 number_format ,将它们隐藏起来,如 this 。搜索其他人的排序方式,我发现了 iDataSort现在我可以格式化显示列中的任何内容。

最佳答案

您需要将字符串转换回 float ,您可以为此定义自己的数据类型(未经测试):

(function(){

var tofloat = function(n) {
return parseFloat(n.replace('.', '').replace(',', '.'));
};

$.fn.dataTableExt.oSort['mynumeric-asc'] = function(a, b) {
a = tofloat(a);
b = tofloat(b)

return ((a < b) ? -1 : ((a > b) ? 1 : 0));
};

$.fn.dataTableExt.oSort['mynumeric-desc'] = function(a, b) {
a = tofloat(a);
b = tofloat(b)

return ((a < b) ? 1 : ((a > b) ? -1 : 0));
};

}());

然后声明"sType": "mynumeric"

作为比较,这是 DataTable 内数字排序的完整代码:

/*
* numerical sorting
*/
"numeric-asc": function ( a, b )
{
var x = (a=="-" || a==="") ? 0 : a*1;
var y = (b=="-" || b==="") ? 0 : b*1;
return x - y;
},

"numeric-desc": function ( a, b )
{
var x = (a=="-" || a==="") ? 0 : a*1;
var y = (b=="-" || b==="") ? 0 : b*1;
return y - x;
}

如您所见,数字的转换是通过将字符串乘以 1 来完成的,它不知道逗号或除小数点分隔符之外的点。

关于php - 数据表按数字字段排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9231143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com