Skip to content
Advertisement

Change array keys of nested array on multidimensional array from integer to alphabet

array (
  'A' => 
  array (
    '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' => 
  array (
    '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'
    )
)

I trying to get each nested array from 0..x to be converted to alphabet. So for example ‘topic’ is ‘A’, and ‘orgkey’ is ‘F’.

Then return a new multidimensional array (‘A’ => array(‘A’ => ‘My topic name’, ‘B’ => ’12/11/2018 16:30:00′)) and so forth.

Advertisement

Answer

Make an array of the alphabet and loop through the array, replacing the key with the letter of the alphabet at the same index.

https://paiza.io/projects/_ICIlEET4tieXtsN4MF4rw

$alph = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');

$arr=array('A'=>array('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'=>array('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'));

$newArr = array();
foreach($arr as $key1 => $val1){
    $i=0;
    foreach($val1 as $key2 => $val2){
        $newKey = "";
        //this if/else statement sets the key from A-Z, then AA, AB, etc.
        if($i > count($alph) - 1){
            $newKey = $alph[floor($i / count($alph)-1)].$alph[$i % count($alph)];
        }else{
            $newKey = $alph[$i];
        }
        $newArr[$key1][$newKey] = $val2;
        $i++;
    }
}

print_r($newArr);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement