note 104952 added to function.sort

From: Date: Mon, 18 Jul 2011 16:14:27 +0000
Subject: note 104952 added to function.sort
Groups: php.notes 
Request: Send a blank email to php-notes+get-181661@lists.php.net to get a copy of this message
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); ?> ---- Server IP: 69.147.83.197 Probable Submitter: 68.0.209.235 ---- Manual Page -- http://www.php.net/manual/en/function.sort.php Edit -- https://master.php.net/note/edit/104952 Del: integrated -- https://master.php.net/note/delete/104952/integrated Del: useless -- https://master.php.net/note/delete/104952/useless Del: bad code -- https://master.php.net/note/delete/104952/bad+code Del: spam -- https://master.php.net/note/delete/104952/spam Del: non-english -- https://master.php.net/note/delete/104952/non-english Del: in docs -- https://master.php.net/note/delete/104952/in+docs Del: other reasons-- https://master.php.net/note/delete/104952 Reject -- https://master.php.net/note/reject/104952 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#181661) next »