Darkkz Darkkz - 1 month ago 6x
PHP Question

Build and fill multi-dimensional associative array from many delimited strings

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


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'];