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

Community
  • 1
  • 1
CarlosAS
  • 654
  • 2
  • 10
  • 31
  • 1
    What code have you tried so far? – gabe3886 Sep 06 '16 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. – CarlosAS Sep 06 '16 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. – gabe3886 Sep 06 '16 at 11:07

1 Answers1

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'];
}
iainn
  • 16,826
  • 9
  • 33
  • 40