<?php
class collection
{
function add($arr)
{
$this->dataSet= $arr;
}
//The wrapper sort function
function sortDataSet($s)
{
//Sort by the given parameter
switch($s)
{
case "title":
//Note use of array to reference member method of this object in callback
uasort($this->dataSet,array($this,"cmpTitle"));
break;
case "pubdate":
uasort($this->dataSet,array($this,"cmpdate"));
break;
}
}
//Callback function for sorting by name
//$a and $b are dataItem objects
function cmpTitle($a,$b)
{
//Use sort() for simple alphabetical comparison
//Convert to lowercase to ensure consistent behaviour
$sortable = array(strtolower($a->name),strtolower($b->name));
$sorted = $sortable;
sort($sorted);
//If the names have switched position, return -1. Otherwise, return 1.
return ($sorted[0] == $sortable[0]) ? -1 : 1;
}
//Callback function for sorting by x
//$a and $b are dataItem objects
function cmpdate($a,$b)
{
//Use sort() for simple alphabetical comparison
//Convert to lowercase to ensure consistent behaviour
$sortable = array(strtolower($a->x),strtolower($b->x));
$sorted = $sortable;
sort($sorted);
//If the names have switched position, return -1. Otherwise, return 1.
return ($sorted[0] == $sortable[0]) ? -1 : 1;
}
}
//Create a collection object
$myCollection = new collection();
$dataSet = array(
array(
'title'=>"salam",
'pubdate'=>"12/5/1386",
),
array(
'title'=>"aleyk",
'pubdate'=>"13/5/1386",
)
);
$myCollection->add($dataSet);
echo "<pre>";
//Sort by title
$myCollection->sortDataSet("title");
echo "بر اساس تایتل سورت میکنه<br>";
print_r($myCollection->dataSet);
//Sort by pubdate
$myCollection->sortDataSet("pubdate");
echo "بر اساس تاریخ سورت میکنه<br>";
print_r($myCollection->dataSet);
?>