PHP Recursive Multidimensional Array Replacement Key Name and Value
Multidimensional Array Key Name Replacement
In many cases, the results are unsatisfactory, and you need to modify them yourself to get an array that meets your needs. You can then modify the key names recursively.
The code is as follows
Code to replace the key name, for example:
function changeKeys($array, $keyEnArray, $keyZhCnArray)
{
if(!is_array($array)) return $array;
$tempArray = array();
foreach ($array as $key => $value){
// Processing keys for arrays, translated into Chinese
$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("Fruits" , "furniture");
$result = changeKeys($info, $keyEnArray, $keyZhCnArray);
print_r($result);
Multidimensional Array Key Value Replacement
In many cases, the results are unsatisfactory and need to be modified before reaching an array that meets the requirements, which can then be modified recursively
The code is as follows
Code to replace the key value, for example:
// Recursively changing the key value of an array
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{
// Processing array values, translating into Chinese
$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("Apple" , "Banana" ,"Pear", "Table", "Chair", "Bed");
$result = changeValues($info, $valueEnArray, $valueZhCnArray);
print_r($result);
Catalog
Use [TOC] to generate directories: