【发布时间】:2010-12-14 15:14:00
【问题描述】:
我有一个有趣的问题。问题的基础是我对数组引用的最后一次迭代没有 如果你愿意的话,似乎会“坚持”。一点背景:我为页面层次结构设计了一个非常简单的数据结构, 看起来像这样:
,1,2,3>,4>,5,6,7
翻译:忘记烦人的前导逗号。第 1、2、3 和 8 页是顶级页面 id,4 是 3 的子页面(“>”表示更深一层),5、6、7 是 4 的子页面。
一种更易读的格式如下所示:
1
2
3
-- 4
-- -- 5
-- -- 6
-- -- 7
8
不要问我为什么要这样做。我还没有想出一种更简单的方法来使用 javascript 生成结构并通过网络表单发布。
问题是在整个递归函数中一切都很好,但是我在调用函数中丢失了第 8 页。我怀疑我在递归、变量引用和变量作用域的某些元素上弄错了,这已经变成了一个难题。
预期输出(在函数的最后一次调用中工作正常):
Array
(
[1] => Array
(
)
[2] => Array
(
)
[3] => Array
(
[4] => Array
(
[5] => Array
(
)
[6] => Array
(
)
[7] => Array
(
)
)
)
[8] => Array
(
)
)
实际输出(循环外):
Array
(
[1] => Array
(
)
[2] => Array
(
)
[3] => Array
(
[4] => Array
(
[5] => Array
(
)
[6] => Array
(
)
[7] => Array
(
)
)
)
)
有什么想法吗?
[编辑]:我删除了几个残留的 self::references...
代码:
<?php
// recursive string in this format: (,\d+)*[>|<]?
// , = leading comma
// n,n+1 = comma-delimited list of page_ids
// > = indicates the next step in our depth-first approach
// < = indicates we're done with that set of children. back it up.
function parse_page_orders($page_orders, &$cur_page, &$trail)
{
// #1 matches our comma-led, comma-delimited list of page id's
// #2 matches our next step--forward or backward
preg_match('/([,\d+]*)([>|<])?/', $page_orders, $matches);
// remove this section of the page_orders variable so we can get on with our lives
$page_orders = str_replace($matches[0], '', $page_orders);
// #1: get the list of page ids and add it to the current page item
$p = explode(',', $matches[1]);
// start at 1 to skip the empty element at the beginning
for ($i=1; $i<count($p); $i++)
{
$cur_page[$p[$i]] = array();
}
// #2: determine our next step
if (isset($matches[2]))
{
if ($matches[2] == '>')
{
$trail[] = &$cur_page;
parse_page_orders($page_orders, $cur_page[end($p)], $trail);
}
elseif ($matches[2] == '<' && count($trail)>0)
{
parse_page_orders($page_orders, array_pop($trail), $trail);
}
}
else
{
// we're done. this should be our result.
print_r($cur_page);
}
}
$pages = array();
$trail = array();
$page_orders = ',1,2,3>,4>,5,6,7<<,8';
parse_page_orders($page_orders, $pages, $trail);
print_r($pages);
?>
【问题讨论】:
标签: php recursion scope pass-by-reference