我需要像这样转换一个结构:
$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 -使多维关联数组从一个分隔的字符串
不确定您遇到了什么问题,但以下工作正常。参见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'];
}