Sort by date function with variable field name

Solution 1:

The PHP construct is use

$date_compare = function ($a, $b) use ($fieldName) {
  ...
}

See https://www.php.net/manual/en/functions.anonymous.php