Home  >  Article  >  Backend Development  >  PHP多维数组怎么替换键名和键值

PHP多维数组怎么替换键名和键值

PHPz
PHPzOriginal
2016-06-06 20:47:173665browse

在PHP中可以使用递归的方法将多维数组的键名和键值进行替换,其具体替换键名和键值的代码方法为“function changeKeys($array, $keyEnArray, $keyZhCnArray){...}”。

PHP多维数组怎么替换键名和键值

PHP递归多维数组替换键名和键值

多维数组键名替换

在很多时候获取到的数组结果不尽人意,需要自己修改后才能的到一个满足需求的数组,这是后可以通过递归的方式修改键名

代码如下

替换键名的代码,例如:

function changeKeys($array, $keyEnArray, $keyZhCnArray)
{
    if(!is_array($array)) return $array;
    $tempArray = array();
    foreach ($array as $key => $value){
        // 处理数组的键,翻译成中文
        $key = array_search($key, $keyEnArray, true) === false ? $key : $keyZhCnArray[array_search($key, $keyEnArray)];
        if(is_array($value)){
            $value = changeKeys($value, $keyEnArray, $keyZhCnArray);
        }
        $tempArray[$key] = $value;
    }
    return $tempArray;
}
$info = array( "fruits" => array("apple", "banana", "pear"), "furniture" => array("table", "chair", "bed"));
$keyEnArray = array("fruits" , "furniture");
$keyZhCnArray = array("水果" , "家具");
$result = changeKeys($info, $keyEnArray, $keyZhCnArray);
print_r($result);

多维数组键值替换

在很多时候获取到的数组结果不尽人意,需要自己修改后才能的到一个满足需求的数组,这是后可以通过递归的方式修改键值

代码如下

替换键值的代码,例如:

// 递归改变数组的键值
function changeValues($array, $valueEnArray, $valueZhCnArray)
{
    if(!is_array($array)) return $array;
    $tempArray = array();
    foreach ($array as $key=>$value){
        if(is_array($value)){
            $value = changeValues($value, $valueEnArray, $valueZhCnArray);
        }else{
            // 处理数组的值,翻译成中文
            $value = array_search($value, $valueEnArray, true) === false ? $value : $valueZhCnArray[array_search($value, $valueEnArray)];
        }
        $tempArray[$key]=$value;
    }
    return $tempArray;
}
$info = array( "fruits" => array("apple", "banana", "pear"), "furniture" => array("table", "chair", "bed"));
$valueEnArray = array("apple" , "banana", "pear", "table", "chair", "bed");
$valueZhCnArray = array("苹果" , "香蕉" ,"梨", "桌子", "椅子", "床");
$result = changeValues($info, $valueEnArray, $valueZhCnArray);
print_r($result);

更多相关技术文章,请访问PHP中文网

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn