PHP's array_map including keys

前端 未结 18 2780
抹茶落季
抹茶落季 2020-11-30 19:31

Is there a way of doing something like this:

$test_array = array(\"first_key\" => \"first_value\", 
                    \"second_key\" => \"second_valu         


        
18条回答
  •  余生分开走
    2020-11-30 20:01

    I'll add yet another solution to the problem using version 5.6 or later. Don't know if it's more efficient than the already great solutions (probably not), but to me it's just simpler to read:

    $myArray = [
        "key0" => 0,
        "key1" => 1,
        "key2" => 2
    ];
    
    array_combine(
        array_keys($myArray),
        array_map(
            function ($intVal) {
                return strval($intVal);
            },
            $myArray
        )
    );
    

    Using strval() as an example function in the array_map, this will generate:

    array(3) {
      ["key0"]=>
      string(1) "0"
      ["key1"]=>
      string(1) "1"
      ["key2"]=>
      string(1) "2"
    }
    

    Hopefully I'm not the only one who finds this pretty simple to grasp. array_combine creates a key => value array from an array of keys and an array of values, the rest is pretty self explanatory.

提交回复
热议问题