您将需要一点递归,因此为了做到这一点,您需要通过引用将 lambda 函数传递给自身:
function mathh($arr, $fn){
$arr2 = []; // moved the array formation out of the for loop so it doesn't get overwritten
for($i = 0; $i < sizeof($arr); $i++){ // starting $i at 0
$arr2[$i] = $fn($arr[$i]);
}
return $arr2;
}
$userDefined = function($value) use (&$userDefined){ // note the reference to the lambda function $userDefined
if(1 == $value) {
return 1;
} else {
return $value * $userDefined($value - 1); // here is the recursion which performs the factorial math
}
};
$arr = [1,2,3,4,5];
$newArray = mathh($arr, $userDefined);
print_r($newArray);
输出:
Array
(
[0] => 1
[1] => 2
[2] => 6
[3] => 24
[4] => 120
)
我想对此进行一些扩展,因为您本质上(在本例中)创建了一个数组映射。这could如果您在函数中进行额外的计算,会很方便mathh()
但如果您只想使用 lambda 函数创建一个具有范围的新数组,您可以这样做(利用我们已经创建的相同 lambda):
$mapped_to_lambda = array_map($userDefined, range(1, 5));
print_r($mapped_to_lambda);
您将得到相同的输出,因为映射数组的范围 (1,5) 与原始数组相同:
Array
(
[0] => 1
[1] => 2
[2] => 6
[3] => 24
[4] => 120
)