从许多分隔的字符串构建和填充多维关联数组

时间:2016-09-06 09:45:04

标签: php arrays multidimensional-array

我需要转换这样的结构:

$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"

这样的事情:

$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"

我发现了类似的问题,但我无法根据问题的特定版本进行调整:PHP - Make multi-dimensional associative array from a delimited string

1 个答案:

答案 0 :(得分:1)

不确定您遇到了什么问题,但以下工作正常。有关演示,请参阅https://eval.in/636072

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