How to rename array keys in PHP?

前端 未结 10 1190
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 03:39

When I var_dump on a variable called $tags (a multidimensional array) I get this:

Array
(
    [0] => Array
        (
            [name] => tabbing
            [url         


        
10条回答
  •  独厮守ぢ
    2020-11-28 04:38

    This should work in most versions of PHP 4+. Array map using anonymous functions is not supported below 5.3.

    Also the foreach examples will throw a warning when using strict PHP error handling.

    Here is a small multi-dimensional key renaming function. It can also be used to process arrays to have the correct keys for integrity throughout your app. It will not throw any errors when a key does not exist.

    function multi_rename_key(&$array, $old_keys, $new_keys)
    {
        if(!is_array($array)){
            ($array=="") ? $array=array() : false;
            return $array;
        }
        foreach($array as &$arr){
            if (is_array($old_keys))
            {
                foreach($new_keys as $k => $new_key)
                {
                    (isset($old_keys[$k])) ? true : $old_keys[$k]=NULL;
                    $arr[$new_key] = (isset($arr[$old_keys[$k]]) ? $arr[$old_keys[$k]] : null);
                    unset($arr[$old_keys[$k]]);
                }
            }else{
                $arr[$new_keys] = (isset($arr[$old_keys]) ? $arr[$old_keys] : null);
                unset($arr[$old_keys]);
            }
        }
        return $array;
    }
    

    Usage is simple. You can either change a single key like in your example:

    multi_rename_key($tags, "url", "value");
    

    or a more complex multikey

    multi_rename_key($tags, array("url","name"), array("value","title"));
    

    It uses similar syntax as preg_replace() where the amount of $old_keys and $new_keys should be the same. However when they are not a blank key is added. This means you can use it to add a sort if schema to your array.

    Use this all the time, hope it helps!

提交回复
热议问题