How to get the keys of each level of a multidimensional array in PHP

Issue

I’m trying to grab all the keys of a multidimensional array and format them a certain way. Here’s a partial array:

$ini_config['aaa']['email']['main'] = '[email protected]';

$ini_config['bbb']['email']['ccc'] = '[email protected]';
$ini_config['bbb']['phone']['local'] = '800-555-1212';
$ini_config['bbb']['phone']['skype'] = '744-222-1234';

$ini_config['ccc']['phone']['main'] = 'domain.com';
$ini_config['ccc']['domain']['https'] = 'https://www. domain.com';
$ini_config['ccc']['fax'] = '744-222-1237';

and here’s the format I need them in:

aaa_email_main
bbb_email_ccc
bbb_phone_local
bbb_phone_skype
ccc_phone_main
ccc_domain_https
ccc_fax

This script is the closest I’ve been able to come to what I need:

<?php
rloop($ini_config);

function rloop($array) {
    global $full_key;

    foreach($array as $key => $value) {
        if(is_array($value) ) {
            $full_key .= $key .'_';
            $array[$key] = rloop($array[$key]);
        }
        else {
            $array[$key] = (string) $value;
            $filename = $full_key . $key;
            echo 'filename: '. $filename . PHP_EOL;
            $full_key = '';
        }
    }
}

N.B. The number of levels can be from 1 to 4, and all keys are strings.

Thanks

Solution

$ini_config['aaa']['email']['main'] = '[email protected]';
$ini_config['bbb']['email']['ccc'] = '[email protected]';
$ini_config['bbb']['phone']['local'] = '800-555-1212';
$ini_config['bbb']['phone']['skype'] = '744-222-1234';
$ini_config['ccc']['phone']['main'] = 'domain.com';
$ini_config['ccc']['domain']['https'] = 'https://www. domain.com';
$ini_config['ccc']['fax'] = '744-222-1237';

function keyPaths(array $array, array $carry = [], string $separator = ''): array {
  foreach ($array as $key => $value) {
    if (is_array($value)) {
      $carry = keyPaths($value, $carry, $separator . $key . '_');
    } else {
      $carry[] = $separator . $key;
    }
  }
  return $carry;
}

$result = keyPaths($ini_config);

Answered By – lukas.j

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published