Looking for array_map equivalent to work on keys in associative arrays

穿精又带淫゛_ 提交于 2019-12-11 23:05:22

问题


Suppose I have an associative array:

    $array = array(
      "key1" => "value",
      "key2" => "value2");

And I wanted to make the keys all uppercase. How would I do than in a generalized way (meaning I could apply a user defined function to apply to the key names)?


回答1:


You can use the array_change_key_case function of php

<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>



回答2:


Amazingly, there's an array_change_key_case function.




回答3:


Apart from the above answers -- the following code also does the trick. The benefit is you can use this for any operation on the keys than only making the keys uppercase.

<?php
   $arr = array(
      "key1" => "value",
      "key2" => "value2"
   );

  echo "<pre>";print_r($arr);echo "</pre>";

  $arra = array_combine(
        array_map(function($k){ 
           return strtoupper($k); 
        }, array_keys($arr)
    ), $arr);

  echo "<pre>";print_r($arra);echo "</pre>";

This code outputs as:

Array
(
    [key1] => value
    [key2] => value2
)
Array
(
    [KEY1] => value
    [KEY2] => value2
)

So this is just an alternative and more generic solution to change keys of an array.

Thanks.




回答4:


You can use a foreach loop:

$newArray = array();
foreach ($array as $k => $v) {
    $newArray[strtoupper($k)] = $v;
}


来源:https://stackoverflow.com/questions/17864729/looking-for-array-map-equivalent-to-work-on-keys-in-associative-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!