replace array keys with given respective keys

前端 未结 10 1155
轻奢々
轻奢々 2020-12-29 09:16

I have an array like below

$old = array(
       \'a\' => \'blah\',
       \'b\' => \'key\',
       \'c\' => \'amazing\',
       \'d\' => array(
          


        
10条回答
  •  一生所求
    2020-12-29 09:51

    This the solution i have implemented for the same subject:

    /**
     * Replace keys of given array by values of $keys
     * $keys format is [$oldKey=>$newKey]
     *
     * With $filter==true, will remove elements with key not in $keys
     *
     * @param  array   $array
     * @param  array   $keys
     * @param  boolean $filter
     *
     * @return $array
     */
    function array_replace_keys(array $array,array $keys,$filter=false)
    {
        $newArray=[];
        foreach($array as $key=>$value)
        {
            if(isset($keys[$key]))
            {
                $newArray[$keys[$key]]=$value;
            }
            elseif(!$filter)
            {
                $newArray[$key]=$value;
            }
        }
    
        return $newArray;
    }
    

提交回复
热议问题