0
static public function sortArrayByDate($array, $table, $fieldName){

$arr_1 = array();
foreach($array as $val_a)
{ 
    $arr_1[] .= $val_a;
    $arr_2 = array();
    foreach($arr_1 as $val_b){
        $obj = Doctrine_Core::getTable("$table")->findOneBy('id', $val_b);
        $arr_2[] = array(
            'id' => $val_b,
            "$fieldName" => $obj->get($fieldName)
        );
    }
}

/*
 * $arr_2 array result looks like:
 * 
 * array[0]
 *      id = 1
 *      date_field = 2013-5-20      //'date_field' name may be variable
 * array[1]
 *      id = 2
 *      date_field = 2012-5-20
 */

$date_compare = function($a, $b)
{         
    if ($a[$fieldName] == $b[$fieldName]) {
    return 0;
    }
    return ($a[$fieldName] < $b[$fieldName]) ? -1 : 1;

};  
usort($arr_2, $date_compare);

return $arr_2;
}

我遇到的问题是将变量 field_name 传递给 date_compare 函数,由于 usort 方法,该函数只能接受两个变量。date_compare 函数也必须包装在一个变量中,以避免在多次调用时重新声明一个函数。我什至以正确的方式去做这件事?

4

1 回答 1

2

PHP 结构是use

$date_compare = function ($a, $b) use ($fieldName) {
  ...
}

https://www.php.net/manual/en/functions.anonymous.php

于 2013-05-24T13:24:25.120 回答