gpt4 book ai didi

php - 如何在 PHP 中转换数组 [嵌套]

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:53:01 25 4
gpt4 key购买 nike

拜托,我需要帮助。如何通过 PHP 转换我的数组

Array
(
[0] => Apple
[1] => Orange
[2] => Tomato
)

为此

Array
(
[Apple] => Array
(
[Orange] => Array
(
[Tomato] => Array()
)

)

)

而且我不知道我的数组中有多少个元素。谢谢大家。

最佳答案

输出

Array
(
[0] => Apple
[1] => Orange
[2] => Tomato
[3] => Banana
[4] => Papaya
)
Array
(
[Apple] => Array
(
[Orange] => Array
(
[Tomato] => Array
(
[Banana] => Array
(
[Papaya] => Array
(
)

)

)

)

)

)

代码

$fruits = [

"Apple",
"Orange",
"Tomato",
"Banana",
"Papaya"

];

// Result Array

$result = [

$fruits[count($fruits) - 1] => []

];

// Process

for ($counter = count($fruits) - 2; $counter >= 0; $counter--) {

$temp = $result;

unset($result);

$result[$fruits[$counter]] = $temp;

}

// Display

echo "<pre>".print_r($fruits, true)."</pre>";
echo "<pre>".print_r($result, true)."</pre>";

关于php - 如何在 PHP 中转换数组 [嵌套],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34410106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com