[英]Create a nested array from flat array using children
我有一個關於嵌套數組的問題; 我在Google和stackoverflow上進行了搜索,但找不到適合我需求的解決方案:-/
我有以下數組:
Array
(
[0] => Array
(
[name] => Europe
[children] => Array
(
[0] => West
[1] => East
[2] => South
[3] => North
[4] => Zimbabwe
)
)
[1] => Array
(
[name] => West
[children] => Array
(
[0] => Germany
[1] => France
[2] => Switzerland
[3] => Netherlands
[4] => Belgium
[5] => Luxembourg
[6] => United Kingdom
[7] => Ireland
)
)
[2] => Array
(
[name] => Germany
[children] =>
)
[3] => Array
(
[name] => France
[children] =>
)
)
我想對其進行轉換以使其嵌套,這意味着:
Array
(
[0] => Array
(
[name] => Europe
[children] => Array
(
[0] => Array
(
[name] => West
[children] => Array
(
[0]=> Array
(
[name] => Germany
)
[1]=> Array
(
[name] => France
)
)
)
[2] => Array
(
[name] => East
[children] => Array
(
[0]=> Array
(
[name] => Poland
)
[1]=> Array
(
[name] => Austria
)
)
)
)
)
)
你有想法嗎 ?
提前致謝!
foreach ($unnested_ary as $one_k => $one_v)
{
foreach ($one_v as $two_k => $two_v)
{
if ($two_k == 'children')
{
foreach ($two_v as $three_k => $three_v)
{
$unnested_array[$one_k][$two_k][$three_k][] = array(array(
'name' => $three_v
));
}
}
}
}
我不確定是否正確嵌套了該嵌套,但是您應該了解這個想法並嘗試使用此代碼。 基本上,這應該像您要求的那樣創建新的鍵和值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.