duansha7025 2012-10-23 17:40
浏览 312
已采纳

PHP array_map包括键

Is there a way of doing something like this:

$test_array = array("first_key" => "first_value", 
                    "second_key" => "second_value");

var_dump(array_map(function($a, $b) { return "$a loves $b"; }, 
         array_keys($test_array), 
         array_values($test_array)));

But instead of calling array_keys and array_values, directly passing the $test_array variable?

The desired output is:

array(2) {
  [0]=>
  string(27) "first_key loves first_value"
  [1]=>
  string(29) "second_key loves second_value"
}
  • 写回答

16条回答 默认 最新

  • duanchen6423 2012-10-23 17:51
    关注

    Not with array_map, as it doesn't handle keys.

    array_walk does:

    $test_array = array("first_key" => "first_value",
                        "second_key" => "second_value");
    array_walk($test_array, function(&$a, $b) { $a = "$b loves $a"; });
    var_dump($test_array);
    
    // array(2) {
    //   ["first_key"]=>
    //   string(27) "first_key loves first_value"
    //   ["second_key"]=>
    //   string(29) "second_key loves second_value"
    // }
    

    It does change the array given as parameter however, so it's not exactly functional programming (as you have the question tagged like that). Also, as pointed out in the comment, this will only change the values of the array, so the keys won't be what you specified in the question.

    You could write a function that fixes the points above yourself if you wanted to, like this:

    function mymapper($arrayparam, $valuecallback) {
      $resultarr = array();
      foreach ($arrayparam as $key => $value) {
        $resultarr[] = $valuecallback($key, $value);
      }
      return $resultarr;
    }
    
    $test_array = array("first_key" => "first_value",
                        "second_key" => "second_value");
    $new_array = mymapper($test_array, function($a, $b) { return "$a loves $b"; });
    var_dump($new_array);
    
    // array(2) {
    //   [0]=>
    //   string(27) "first_key loves first_value"
    //   [1]=>
    //   string(29) "second_key loves second_value"
    // }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(15条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置