【发布时间】:2012-06-10 23:43:20
【问题描述】:
所以我的示例输入是
$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 请求。我们想帮助您,而不是为您工作;)再试一次并发布结果。 -
感谢您发布代码。别担心。与他人分享并获得反馈总是一种很好的学习体验。
-
大部分递归性质可以使用
array_merge_recursive解决,其余的都是尾递归的,因此可以迭代解决:)
标签: php recursion multidimensional-array