Custom Sort

December 15th, 2016

New: as of version 2.8, easier and more sorting options are available via sorting with Transforms.

Issue: how to create a custom sort when creating your own short code.

This code requires PHP 4.2 or later.

Example: sort form entries by “age” field, treating all the values as numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// first add a sorting callback function.
// Set the $field to the field you want
/**
 * Custom sorting function for a particular form
 * to be used as in input to uasort()
 * Requires PHP 4.2.0 or later
 * @param $a array (associative)
 * @param $b array (associative)
 * @return int -1 for $a<$b, 0 for $a==$b, 1 for $a>$b
 */
function mysort($a, $b) {
  $field = 'age'; // Change to your field name to sort on
  $aVal = floatval($a[$field]);
  $bVal = floatval($b[$field]);
  if ($aVal == $bVal) {
    return 0;
    // or sort by a secondary field here
  }
  // for DESC sort change < to > below
  return $aVal < $bVal ? -1 : 1;
}
 
// Add the regular code here from "Create your own short code" page
require_once(ABSPATH . 'wp-content/plugins/contact-form-7-to-database-extension/CFDBFormIterator.php');
$exp = new CFDBFormIterator();
$exp->export($atts['form'], $atts);
$rows = array();
while ($row = $exp->nextRow()) {
  // instead of creating output, just save the data into an array
  $rows[] = $row;
}
// Sort the array using the sort callback function
uasort($rows, 'mysort');
foreach($rows as $row) {
  // Replace with your code to output data here
  echo '<pre>';
  print_r($row);
  echo '</pre>';
}</pre>
  1. johnja1
    June 4th, 2014 at 09:54 | #1

    Hey Micheal,

    I found this function and PHP on your site, Will it work as orderby ? Please let me know

    // first add a sorting callback function.
    // Set the $field to the field you want
    /**
    * Custom sorting function for a particular form
    * to be used as in input to uasort()
    * Requires PHP 4.2.0 or later
    * @param $a array (associative)
    * @param $b array (associative)
    * @return int -1 for $a$b
    */
    function mysort($a, $b) {
    $field = ‘age’; // Change to your field name to sort on
    $aVal = floatval($a[$field]);
    $bVal = floatval($b[$field]);
    if ($aVal == $bVal) {
    return 0;
    // or sort by a secondary field here
    }
    // for DESC sort change below
    return $aVal export($atts[‘form’], $atts);
    $rows = array();
    while ($row = $exp->nextRow()) {
    // instead of creating output, just save the data into an array
    $rows[] = $row;
    }
    // Sort the array using the sort callback function
    uasort($rows, ‘mysort’);
    foreach($rows as $row) {
    // Replace with your code to output data here
    echo ”;
    print_r($row);
    echo ”;
    }

    Thanks
    Jacob

Comments are closed.  Go To Support Forum