Friday, July 1, 2022

quick reminder to self: how to sort array by a field in the map-ish objects in php

Just one of those small things I was surprised I hadn't already noted on my devblog, in PHP, to sort an array of objects / array of maps, based on a field in all the maps, it's the usort command which works in place on the array, and with the second argument being (weirdly) a string version of the function name:

    usort($allresponses,"sortOnFirstField");

     function sortOnFirstField($a,$b) {

        global $firstkey;

        return strcmp($a[$firstkey],$b[$firstkey]);

    }

The weirdness of using a stringname... definitely oldschool. Javascript is obviously a bit slicker, though I still appreciate how PHP splits the differences with globals that I have to use instead... (YES you can use them, but also YES you have to acknowledge that you are using on in a function)


Oh and while I am at it, replace special characters etc in a string:

function clean($string) {

   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

}

No comments:

Post a Comment