如何在 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
广告