note 23305 modified in function.usort by danbrown

From: Date: Sun, 23 Jan 2011 16:31:59 +0000
Subject: note 23305 modified in function.usort by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-176083@lists.php.net to get a copy of this message
Here is a simple example of converting a timestamp date("U") into a date. This sorts by that day and then by string value alphabetically. I hope it saves someone some time... Happy PHP'in! <?php //data to sort $shared[0]["page_id"] = "2025731470"; $shared[1]["page_id"] = "2025731450"; $shared[2]["page_id"] = "1025731456"; $shared[3]["page_id"] = "1025731460"; $shared[0]["username"] = "larry"; $shared[1]["username"] = "alvin"; $shared[2]["username"] = "garth"; $shared[3]["username"] = "harvy"; //function to convert timestamp to date function convert_timestamp($timestamp){ $limit=date("U"); $limiting=$timestamp-$limit; return date ("Ymd", mktime (0,0,$limiting)); } //comparison function function cmp ($a, $b) { $l=convert_timestamp($a["page_id"]); $k=convert_timestamp($b["page_id"]); if($k==$l){ return strcmp($a["username"], $b["username"]); }else{ return strcmp($k, $l); } } //sort array usort($shared, "cmp"); //display sorted info while (list ($key, $value) = each ($shared)) { echo "\$shared[$key]: "; echo $value["page_id"]; echo " username: "; echo $value["username"]; echo "<break_tag>"; } ?> This will output: $shared[0]: 2025731450 username: alvin $shared[1]: 2025731470 username: larry $shared[2]: 1025731456 username: garth $shared[3]: 1025731460 username: harvy --was-- Here is a simple example of converting a timestamp date("U") into a date. This sorts by that day and then by string value alphabetically. I hope it saves someone some time... Happy PHP'in! //data to sort $shared[0]["page_id"] = "2025731470"; $shared[1]["page_id"] = "2025731450"; $shared[2]["page_id"] = "1025731456"; $shared[3]["page_id"] = "1025731460"; $shared[0]["username"] = "larry"; $shared[1]["username"] = "alvin"; $shared[2]["username"] = "garth"; $shared[3]["username"] = "harvy"; //function to convert timestamp to date function convert_timestamp($timestamp){ $limit=date("U"); $limiting=$timestamp-$limit; return date ("Ymd", mktime (0,0,$limiting)); } //comparison function function cmp ($a, $b) { $l=convert_timestamp($a["page_id"]); $k=convert_timestamp($b["page_id"]); if($k==$l){ return strcmp($a["username"], $b["username"]); }else{ return strcmp($k, $l); } } //sort array usort($shared, "cmp"); //display sorted info while (list ($key, $value) = each ($shared)) { echo "\$shared[$key]: "; echo $value["page_id"]; echo " username: "; echo $value["username"]; echo "<break_tag>"; } //This will output: $shared[0]: 2025731450 username: alvin $shared[1]: 2025731470 username: larry $shared[2]: 1025731456 username: garth $shared[3]: 1025731460 username: harvy http://php.net/manual/en/function.usort.php

« previous php.notes (#176083) next »