1 回答

TA貢獻1815條經驗 獲得超13個贊
發生了 Stack Overflow 奇跡......我得到了一個遞歸代碼片段來處理第一遍!通常我要花一兩個小時才能寫出有用的東西。
我不知道我是否可以使它更緊/更好,或者它是否會在任何邊緣情況下失敗,但是:
它適用于您的樣本輸入
對我來說現在是午夜,我累了,我必須在早上工作
實際上,只要結構數組中存在相同級別的鍵,它就會同步遞歸地迭代每個數組并將條目數組的每個級別存儲到輸出數組。
代碼:(演示)
function truncateRecursive($structure, $entry) {
$output = [];
while (($structureKey = key($structure)) !== null && ($entryKey = key($entry)) !== null) {
$output[$entryKey] = !is_array($entry[$entryKey])
? $entry[$entryKey]
: truncateRecursive($structure[$structureKey], $entry[$entryKey]);
unset($structure[$structureKey], $entry[$entryKey]);
}
return $output;
}
var_export(truncateRecursive($structure, $entry));
輸出:
array (
157 =>
array (
'id' => '157',
'username' => 'test1',
'children' =>
array (
0 =>
array (
'id' => '158',
'username' => 'test1',
'children' =>
array (
0 =>
array (
'id' => '159',
'username' => 'test2',
'children' =>
array (
0 =>
array (
'id' => '160',
'username' => 'test3',
'children' =>
array (
),
),
),
),
),
),
),
),
)
- 1 回答
- 0 關注
- 157 瀏覽
添加回答
舉報