假设我们有以下数组-
$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