1

I need to convert an structure like this:

$source[0]["path"]; //"production.options.authentication.type"
$source[0]["value"]; //"administrator"
$source[1]["path"]; //"production.options.authentication.user"
$source[1]["value"]; //"admin"
$source[2]["path"]; //"production.options.authentication.password"
$source[2]["value"]; //"1234"
$source[3]["path"]; //"production.options.url"
$source[3]["value"]; //"example.com"
$source[4]["path"]; //"production.adapter"
$source[4]["value"]; //"adap1"

into something like this:

$result["production"]["options"]["authentication"]["type"]; //"administrator"
$result["production"]["options"]["authentication"]["user"]; //"admin"
$result["production"]["options"]["authentication"]["password"]; //"1234"
$result["production"]["options"]["url"]; //"example.com"
$result["production"]["adapter"]; //"adap1"

I found a similar question but I can't adapt it to my particular version of the problem: PHP - Make multi-dimensional associative array from a delimited string

3
  • 1
    What code have you tried so far? Commented Sep 6, 2016 at 10:58
  • I tried to adapt the choosen answer of the question I linked, but it only builds the array from one string and I can't make it build the array from multiple strings (without replacing the structure) and fill the values. Commented Sep 6, 2016 at 11:04
  • can you post the code you have, even if it's not working. That way we can see what you've tried and maybe pin-point what's not working. Commented Sep 6, 2016 at 11:07

1 Answer 1

2

Not sure what problems you were running into, but the following works ok. See https://eval.in/636072 for a demo.

$result = [];

// Each item in $source represents a new value in the resulting array
foreach ($source as $item) {
    $keys = explode('.', $item['path']);

    // Initialise current target to the top level of the array at each step
    $target = &$result;

    // Loop over each piece of the key, drilling deeper into the final array
    foreach ($keys as $key) {
        $target = &$target[$key];
    }

    // When the keys are exhausted, assign the value to the target
    $target = $item['value'];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Totally solving the problem. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.