duanjucong3124 2015-12-03 11:34 采纳率: 100%
浏览 84
已采纳

寻找类似于array_map的函数,但每次回调时都使用相同的arg

As someone who is learning PHP I was experimenting with the arrap_map function. I was hoping that it would pass the same 3rd arg each time through to the called function. As below, this is not the behaviour of array_map. Is there an alternative function I can use to achieve this?

$arr = [['a'], ['b'], ['c']];
$args = ['set'];

function mapper($item, $arg){
return $item[] = $arg;
}
$result = array_map('mapper', $arr, $args);

only the first element has 'set' as a value

 $arr = [['a'], ['b'], ['c']];
$args = ['set', 'set', 'set'];

function mapper($item, $arg){
return $item[]  = $arg;
}

$result = array_map('mapper', $arr, $args);

all three elements have 'set' as a value

  • 写回答

1条回答 默认 最新

  • douzai1074 2015-12-03 12:29
    关注

    Your code is incorrect, $a[$b] doesn't make any sense. Both variables are strings.

    Your output also doesn't make sense, quoting from the manual:

    If more than one argument is passed then the returned array always has integer keys.


    To answer your question, it's a language design choice.

    It could

    • pass NULL for missing elements (that was PHP does).
    • throw an error if the inputs don't have the same size.
    • cycle the smaller inputs.

    All these have valid applications and their own problems.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料