如何将PHP多维数组中嵌套子数组的键替换为顺序字母索引
PHP 数组键名替换实现方案
核心逻辑
- 利用PHP数组的有序特性,严格保留子数组原有字段的排列顺序
- 按字段在子数组中的顺序位置(从0开始计数),通过ASCII码偏移生成对应大写字母作为新键(位置0对应
A、1对应B,以此类推) - 保留顶层数组的原有键(A、B),仅替换嵌套子数组的键名
实现代码
// 原始输入数组 $original = [ 'A' => [ 'topic' => 'My topic name', 'starttime' => '12/11/2018 16:30:00', 'endtime' => '12/11/2018 18:00:00', 'webinarid' => '1235', 'webinarkey' => '123518238123', 'orgkey' => '', 'regurl' => 'https://attendee.gotowebinar.com/register/xxx', 'description' => 'Long desc', 'newsletteremailid' => '321', 'ogimage' => 'https://xxx', 'presenterurl' => 'https://xxx', 'elite' => '1', 'postid' => '699599', ], 'B' => [ 'topic' => 'Topic title', 'starttime' => '12/4/2018 16:30:00', 'endtime' => '12/4/2018 18:00:00', 'webinarid' => '123512', 'webinarkey' => '8127317327132', 'orgkey' => '', 'regurl' => 'https://attendee.gotowebinar.com/register/xxx', 'description' => 'Topic description', 'newsletteremailid' => '316', 'ogimage' => 'https://xxx', 'presenterurl' => '', 'elite' => '1', 'postid' => '8235123' ] ]; $result = []; foreach ($original as $topKey => $subArr) { $newSub = []; // 转索引数组后按顺序遍历,保证位置计数准确 foreach (array_values($subArr) as $position => $value) { $newKey = chr(ord('A') + $position); $newSub[$newKey] = $value; } $result[$topKey] = $newSub; } // 验证输出 print_r($result);
输出效果(顶层A子数组节选)
// 仅展示前2个字段,其余按顺序对应C~M [ 'A' => 'My topic name', 'B' => '12/11/2018 16:30:00', // ... ]
注:当前场景子数组共13个字段,单字母(A~M)完全覆盖;若后续字段数量超过26个,可扩展
$newKey的生成逻辑支持双字母(如AA、AB)格式。
内容的提问来源于stack exchange,提问作者ctrlbrk
相关产品推荐
相关产品推荐

