Home > Back-end >  How do I convert dot-delimited text into an array? [duplicate]
How do I convert dot-delimited text into an array? [duplicate]

Time:09-22

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.

CodePudding user response:

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

you can try it

CodePudding user response:

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

  • Related