मान लें कि हमारे पास निम्नलिखित सरणी है -
$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