将字符串的平面数组转换为关联数组

时间:2019-12-13 08:50:58

标签: php

我要转换此字符串数组;

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

转换为这种格式。

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

对不起,您未发布一些代码。

这是我尝试过的,

<?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>";

1 个答案:

答案 0 :(得分:0)

我使用以下代码从网上找到了解决方案;

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