我有这个
$ids = array_map(array($this, 'myarraymap'), $data['student_teacher']);
function myarraymap($item) {
return $item['user_id'];
}
我想在我的函数中添加一个其他参数来得到类似的东西
function myarraymap($item,$item2) {
return $item['$item2'];
}
有人可以帮助我吗?我尝试了很多东西,但没有任何效果
最佳答案
您可以使用 anonymous function并以这种方式将局部变量的值传输到您的 myarraymap
第二个参数中:
function myarraymap($item,$item2) {
return $item[$item2];
}
$param = 'some_value';
$ids = array_map(
function($item) use ($param) { return myarraymap($item, $param); },
$data['student_teacher']
);
通常只在匿名函数体内传递值就足够了:
function($item) { return myarraymap($item, 'some_value'); }
从 PHP 7.4 开始,您可以使用 arrow functions (这基本上是具有更简洁语法的短匿名函数)以获得更简洁的代码:
$ids = array_map(
fn($item) => myarraymap($item, $param),
$data['student_teacher']
);
关于php - 带参数的php中的Array_map函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8745447/