所以我的例子輸入是如何通過遞歸將此數組轉換爲多維數組?
$example_1 = Array (
0 => Array (
'category' => 'body',
'sub-category' => 'intro',
'id' => 'header',
'copy' => 'Hello',
),
1 => Array (
'category' => 'body',
'sub-category' => 'intro',
'id' => 'footer',
'copy' => 'Bye',
),
);
$example_2 = Array (
0 => Array (
'category' => 'body',
'sub-category' => 'intro',
'sub-sub-category' => 'header',
'sub-sub-child-category' => 'left',
'id' => 'title',
'copy' => 'Hello',
),
1 => Array (
'category' => 'body',
'sub-category' => 'intro',
'sub-sub-category' => 'footer',
'sub-sub-child-category' => 'right',
'id' => 'title',
'copy' => 'Bye',
),
);
我想把它改造成
$example_output_1 = Array (
'body' => Array (
'intro' => Array (
'header' => Array (
'title' => 'Hello',
),
'footer' => Array (
'title' => 'Bye',
),
),
),
);
$example_output_2 = Array (
'body' => Array (
'intro' => Array (
'header' => Array (
'left' => Array (
'title' => 'Hello',
),
),
'footer' => Array (
'right' => Array (
'title' => 'Bye',
)
),
),
),
);
注意數組的深度是動態的(沒有設置 - 僅通過一次點擊「複製'它是否表示數組的深度)。
我有問題試圖正確地獲得遞歸。我使用的基本但非常粗略的算法是 - 循環遍歷行 - 遍歷行內容 - 當索引爲「複製」時,最終值爲當前值。 - 然後建立陣列
我設法讓它只處理一行數組,但它非常混亂,有點斑駁,所以我感覺我真的需要從頭開始。 更新:附加的要求令人尷尬的代碼(不要尖叫,P!)
function buildArray($row, $start = true) {
if ($start) {
$result = array();
}
if (! is_array($row)) {
return $row;
}
// Get the first element of the array include its index
$cellValue = null;
$colId = null;
foreach($row AS $index => $value) {
$cellValue = $value;
$colId = $index;
break;
}
// Reduce the array by one
$tempRow = $row;
$temp = array_shift($tempRow);
if ($colId == 'copy') {
$result[$cell] = buildArray($cellValue, $locale, false);
} else {
$result[$cell] = buildArray($tempRow, $locale, false);
}
return $result;
}
任何幫助將不勝感激。
聽起來很直截了當。你不能把你的算法描述變成實際的'foreach'循環嗎?否則,這種類似於* gimme teh codez *請求。我們想幫助你,而不是爲你工作;)再給它一次併發布結果。 – webbiedave
感謝您發佈代碼。別煩惱。總是一個良好的學習經驗,與他人分享並獲得反饋。 – webbiedave
大部分的遞歸性質可以通過使用'array_merge_recursive'來解決,其餘的都是尾遞歸的,所以可以迭代求解:) –