duanguangwang5829 2013-07-03 18:48 采纳率: 0%
浏览 397
已采纳

如何使用array_map来指定键?

Using the canonical PHPdoc example, this code:

<?php
function cube($n)
{
    return($n * $n * $n);
}

$a = array( 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>

outputs

Array

(
    [0] => 27
    [1] => 64
    [2] => 125
)

But what I really want it to output is something along these lines: Array

(
    [3] => 27
    [4] => 64
    [5] => 125
)

That is, I want the array_map to use the same keys as in the original array. Is there any way to do that? Thanks!

  • 写回答

4条回答 默认 最新

  • douweng1904 2013-07-03 18:50
    关注

    Use array_combine():

    $b = array_combine( $a, array_map("cube", $a));
    

    You can see from this demo that it produces:

    Array
    (
        [3] => 27
        [4] => 64
        [5] => 125
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作