简体   繁体   中英

Convert flat array of string into associative array

I want to convert this array of string;

$arList = ["the","quick","brown","fox"];

into this format.

[
   "the" => [
        "quick" => [
            "brown" => []
        ]
   ]
]

Sorry for not posting some code.

here is what I tried,

<?php

$arList = ["the","quick","brown","fox"];

$newList = [];
$pointer = $newList;
foreach($arList as $item) {
    $pointer[$item] = [];
    $pointer = &$newList[$item];
}

echo "<pre>";
print_r($newList);
echo "</pre>";

I found a solution from the net using the following code;

$result = array_reduce(array_reverse($arList), function($prevArray, $key){
    return $prevArray ? [$key => $prevArray] : [$key];
}, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM