如何从PHP中的简单数组构建动态关联数组?
假设我们有以下数组-
$namesArray = ['John', 'Adam', 'Robert'];
我们想要以下输出,即上述数组的关联数组-
Array ( [John] => Array ( [Adam] => Array ( [Robert] => Smith ) ) )
示例
<!DOCTYPE html><html>
<body>
<?php
function buildingDynamicAssociativeArray($nameArr, $lastName) {
if (!count($nameArr)) {
return $lastName;
}
foreach (array_reverse($nameArr) as $key) {
$dynamicAssociativeArr = [$key => $lastName];
$lastName = $dynamicAssociativeArr;
}
return $dynamicAssociativeArr;
}
$namesArray = ['John', 'Adam', 'Robert'];
$result = buildingDynamicAssociativeArray($namesArray, 'Smith');
print_r($result);
$namesArray = [];
$result1 = buildingDynamicAssociativeArray($namesArray, 'Doe');
echo "";
print_r($result1);
?>
</body>
</html>
输出结果
Array ( [John] => Array ( [Adam] => Array ( [Robert] => Smith ) ) )Doe
以上是 如何从PHP中的简单数组构建动态关联数组? 的全部内容, 来源链接: utcz.com/z/327313.html