lan*_*n.w 2 php arrays replace key multidimensional-array
鉴于此数组:
$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,
),
);
Run Code Online (Sandbox Code Playgroud)
我需要一个函数( replaceKey($array, $oldKey, $newKey)) 用一个新键替换任何键“一”、“二”、“三”、“四”或“五”,而与该键的深度无关。我需要该函数返回一个具有相同 order和structure的新数组。
我已经尝试使用这些问题的答案,但我找不到一种方法来保持顺序并访问数组中的第二级:
这是我行不通的尝试:
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;
}
Run Code Online (Sandbox Code Playgroud)
问候
此函数应替换$oldKeywith 的所有实例$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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3358 次 |
| 最近记录: |