-3

I want to convert dot delimited text into array.

Sample input:

"config.google.api.key"

The output I want:

$output['config']['google']['api']['key']

How can I do it?

Thanks.

Onur KAYA
  • 234
  • 1
  • 9
  • Hi, please provide an [mcve] when asking a question. You're looking for the `explode` function. `$my_string = "config.google.api.key"; $my_array = explode( '.', $my_string);` https://www.php.net/manual/en/function.explode.php – admcfajn Sep 22 '21 at 06:02
  • you can try $flip = array_flip($ex); – IQBAL AHMED Sep 22 '21 at 06:09

2 Answers2

0
$ts = "config.google.api.key";
$ex = explode('.', $ts);

you can try it

IQBAL AHMED
  • 61
  • 1
  • 5
  • Because this question is easily researched elsewhere it shouldn't be answered, but instead flagged for closure. Instead, try a comment. You should have the ability to make comments if you have >50 rep points. – admcfajn Sep 22 '21 at 06:05
  • This might be a correct answer, but it doesn't produce what was asked for. The output here is: `['config','google','api','key']`. – KIKO Software Sep 22 '21 at 06:05
  • $flip = array_flip($ex); Array ( [config] => 0 [google] => 1 [api] => 2 [key] => 3 ) – IQBAL AHMED Sep 22 '21 at 06:09
0

You can create a function that splits on ., and loops over the array you have, and obtains the final index. Here it splits on ., which produces an array ['config','google','api','key'], which are the keys you want to access. You can then loop this array, and chain on the subsequent index until you reach the end - then return that value.

function dotToIndex($array, $string) {
    $parts = explode('.', $string);
    $element = $array;
    foreach ($parts as $part) {
        $element = $element[$part];
    }
    return $element;
}

As an example, the above function with the following code

$myData = [
    'config' => [
        'google' => [
            'api' => [
                'key'=> 'secret',
            ]
        ]
    ]
];

echo dotToIndex($myData, "config.google.api.key");

Would return the index at config.google.api.key,

secret

Qirel
  • 25,449
  • 7
  • 45
  • 62