dougu3290 2019-01-18 17:15
浏览 208

如何访问array_reduce中的当前索引?

Having read this SO post, In PHP I am aware that you can get the index under iteration with array_map as such:

array_map(function($item, $index) { ... }, $items, array_keys($items));

How can I get the an $index available to me when I use array_reduce? I have tried:

array_reduce($items, array_keys($items), function($acc, $item, $index) { ... }, array());

array_reduce($items, function($acc, $item, $index) { ... }, array(), array_keys($items));

But I still can't seem to get $index in an array_reduce. Has anyone successfully done this before?

EDIT

Here's some context as to why I am asking this question.

I do not want to use foreach because I would have to mutate an array outside of the foreach in order to create my collection. I would prefer to avoid mutation.

Other languages allow one to use reduce and get access to the current index like in JavaScript and Ruby. I was hoping to get the same feature in PHP. Oh well! Looks like I'm going to have to use a foreach to create my array while also having the current index under iteration.

  • 写回答

5条回答 默认 最新

  • doujianzi8521 2019-01-18 17:37
    关注

    What you're aware about the getting index in array_reduce doesn't exist. Check documentation.

    The question is why?

    Look, reduce is being used for the purpose of getting down to one single value, it's aggregation. You have initial value, and next value, show your reduce strategy. There is no point in knowing current item index.

    In some other languages, they might provide current index, but not for this array_reduce in PHP. It's language and function designed, there are some constraints in implementation.

    But it doesn't mean you can't have it. You can have it, but not through callback!

    $i = 0;
    $data = [1, 2, 3, 4];
    
    // (1) 
    $result = array_reduce($data, function ($c, $i) { return $c + $i; }, 0);
    
    // (2)
    array_reduce($data, function ($c, $i) { echo "$i
    "; $i++; return $c + $i; }, 0);
    

    The thing is, the function is designed to do this. Or you're trying to use a wrong function. Some other functions might be what you're looking for.

    Or you can write a function that do it, too :)

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值