I am trying to create a function to initiate date_compare() which is a usort
function for a specific array and key.
function init_date_compare($key, $array) {
$key2 = $key;
function date_compare($a, $b) {
global $key2;
$t1 = strtotime($a[$key2]); $t2 = strtotime($b[$key2]);
return $t2 - $t1;
}
usort($array, "date_compare");
}
$arr = array(array("Aug-2-2012"), array("June-2-2012"));
$arr = init_date_compare(0, $arr);
print_r($arr);
This outputs:
Notice: Undefined index: in...
(So basically null, the scoping did not work).
I am not sure how scoping works with functions inside functions, but if I remember right, it is possible. I tried throwing in some global
s and initializing $key2
but I am unable to get this to work.
The reason your code isn't working is because global $key2;
inside the date_compare()
function will not look for it inside the scope init_date_compare()
; rather it will expect to find it inside the global scope.
Besides that, either the array should be passed by reference (i.e. &$array
) via the function parameters, or the array should be returned from it.
Closures would make this a whole lot nicer (PHP >= 5.3):
function init_date_compare($key, &$array)
{
usort($array, function(array $a, array $b) use ($key) {
$t1 = strtotime($a[$key]); $t2 = strtotime($b[$key]);
return $t2 - $t1;
});
}
Another way is by using an object to encapsulate the state:
class DateComparer
{
private $key;
public function __construct($key)
{
$this->key = $key;
}
public function compare(array $a, array $b)
{
$t1 = strtotime($a[$this->key]); $t2 = strtotime($b[$this->key]);
return $t2 - $t1;
}
}
function init_date_compare($key, &$array)
{
usort($array, array(new DateComparer($key), 'compare'));
}
Of course that Jacks answer is the RIGHT WAY of doing things, but just in case you wondered why it didn't work in the first place:
declaring $key2
as global variable is only one problem, the other problem is that the function init_date_compare
does not return the sorted array.
The following code will work:
$key2=0;
function init_date_compare($key, $array) {
global $key2;
$key2 = $key;
function date_compare($a, $b) {
//global $key2;
$t1 = strtotime($a[$key2]); $t2 = strtotime($b[$key2]);
return $t2 - $t1;
}
usort($array, "date_compare");
return $array;
}
$arr = array(array("Aug-2-2012"), array("June-2-2012"));
$arr = init_date_compare(0, $arr);
print_r($arr);