I have a question about jquery DataTable!

Asked 2 years ago, Updated 2 years ago, 132 views

I have a question because there was a problem in the process of making and sorting tables through DataTable.

All are well aligned, but the data in one column of the table is in the format shown below.

12 (10%)
37 (2.1%)
1 (0.2%)
111 (1.8%)

I have the above data format, but when I press Sort, I want it to be sorted based on %.

How can we recognize the numbers in () and sort them out?

jquery datatables sorting

2022-09-21 10:10

1 Answers

If the actual DB data from SELECT * is a string containing a percentage value... We should give up performance and apply custom sort to pass it over to the response. (As we can see in this case, this is a bad form of data. For example, a separate column with a name such as percentage exists, and there should be only those percentage values. It's easier said than done.)

This is what PHP does. Just look at the sequence/principle of development.

// Variable description
// $data is an array of filtered data
// $orderBy is a column of sorting criteria beyond datable
// $orderDirection is the alignment direction beyond datable (asc/desc)

// Assume the column name in question is 'col3'
if ($orderBy == 'col3') {

    // The usort (array, callback (a, b) function sorts the array according to the callback result.
    // This callback should return a negative number if, for example, a must precede it.
    usort($data, function ($a, $b) use ($orderDirection) {

        // String splitting techniques obtain the string in parentheses.
        // Because of this, it's too hard to match regex repeatedly.
        $rightSideA = explode(' (', $a['col3'])[1];
        $percentageA = (float) str_replace('%)', '', $rightSideA);
        $rightSideB = explode(' (', $b['col3'])[1];
        $percentageB = (float) str_replace('%)', '', $rightSideB);

        // Since you obtained two float, sort them by this.
        return $orderDirection == 'desc' ?
            $percentageB - $percentageA :
            $percentageA - $percentageB;
    });

}


2022-09-21 10:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.