给定这个数组:
$list = array(
'one' => array(
'A' => 1,
'B' => 100,
'C' => 1234,
),
'two' => array(
'A' => 1,
'B' => 100,
'C' => 1234,
'three' => array(
'A' => 1,
'B' => 100,
'C' => 1234,
),
'four' => array(
'A' => 1,
'B' => 100,
'C' => 1234,
),
),
'five' => array(
'A' => 1,
'B' => 100,
'C' => 1234,
),
);
我需要一个函数(replaceKey($array, $oldKey, $newKey)
) 来替换任意键“一”、“二”、“三”、“四”或“五”与新键独立于该键的深度。我需要函数返回一个新数组,具有相同的顺序和结构。
我已经尝试使用这个问题的答案,但我找不到保持顺序并访问数组中的第二级的方法:
Changing keys using array_map on multidimensional arrays using PHP
Change array key without changing order
PHP rename array keys in multidimensional array
这是我的尝试,但行不通:
function replaceKey($array, $newKey, $oldKey){
foreach ($array as $key => $value){
if (is_array($value))
$array[$key] = replaceKey($value,$newKey,$oldKey);
else {
$array[$oldKey] = $array[$newKey];
}
}
return $array;
}
问候
最佳答案
此函数应将 $oldKey
的所有实例替换为 $newKey
。
function replaceKey($subject, $newKey, $oldKey) {
// if the value is not an array, then you have reached the deepest
// point of the branch, so return the value
if (!is_array($subject)) return $subject;
$newArray = array(); // empty array to hold copy of subject
foreach ($subject as $key => $value) {
// replace the key with the new key only if it is the old key
$key = ($key === $oldKey) ? $newKey : $key;
// add the value with the recursive call
$newArray[$key] = replaceKey($value, $newKey, $oldKey);
}
return $newArray;
}
关于php - 如何替换多维数组中的键并保持顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35213277/