note 104952 deleted from function.sort by cmb
| From: | cmb@php.net | Date: | Sun, 27 Oct 2019 08:40:42 +0000 |
| Subject: | note 104952 deleted from function.sort by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212798@lists.php.net to get a copy of this message | ||
Note Submitter: holdoffhunger at gmail dot com
----
I have discovered an interesting trick with the sort function. Many coders are using it to sort
options for a user, because a computer will only need sorted data in limited cases. However, every
coder wants their sorted data to be usable. It's very common to find any sorted data online,
and to find options, "Sort by Date," "Sort Alphabetically," etc., etc., whether
you're looking at an online catalogue or some bulletin board.
The trick is to use a combination of html commenting and str_pad's to do definitive "sort
by" functions. Let me demonstrate with an example: consider two arrays, Sorted_By_Date and
Sorted_By_Name. You want every element to be "<option value=something>Option
Name</option", so that you can do a simple foreach statement that prints every option value.
But, sorting these arrays will technically sort just sort whatever you put into "value".
So, here's a neat trick. Make every entry "<!-- Sort_Value --><option
value=something>Option Name</option." That way, when you sort, it'll have to sort
technically by whatever is the Sort_Value.
The greatness of this trick is that you can make as many "sort this data by X" fields as
you want! Just create multiple arrays, each with the same option values and names, but with a
different value put in "Sort_Value", which could be a date, a name, a price, etc.. With
numbers, you may need to use the str_pad function, to push all of the zeros out to the left, for a
proper sort. For instance, in my code, that looks like...
<?php
$number_of_versions_sort_value = str_pad($number_of_versions, 20, "0", STR_PAD_LEFT);
?>