In PHP, how do you change the key of an array element?

后端 未结 23 2805
逝去的感伤
逝去的感伤 2020-11-22 03:45

I have an associative array in the form key => value where key is a numerical value, however it is not a sequential numerical value. The key is actually an I

23条回答
  •  佛祖请我去吃肉
    2020-11-22 04:35

    If you want to replace several keys at once (preserving order):

    /**
     * Rename keys of an array
     * @param array $array (asoc)
     * @param array $replacement_keys (indexed)
     * @return array
     */
    function rename_keys($array, $replacement_keys)  {
          return array_combine($replacement_keys, array_values($array));
    }
    

    Usage:

    $myarr = array("a" => 22, "b" => 144, "c" => 43);
    $newkeys = array("x","y","z");
    print_r(rename_keys($myarr, $newkeys));
    //must return: array("x" => 22, "y" => 144, "z" => 43);
    

提交回复
热议问题