【发布时间】:2011-06-25 07:39:30
【问题描述】:
我有一个脚本可以处理另一个页面上父/子元素的命名。名称的格式类似于E5-2-3,代表第五个元素的第二个子元素的第三个子元素。
我需要做的是将父名称传递给函数并返回下一个孩子的名称。该值将是最后一个孩子的增量,如果是第一个孩子,则为 1。
(我希望这对某人有意义)
索引数组看起来像这样:
1=>null
2=>null
3=>
1=>null
2=>null
3=>
1=>null
4=>null
5=>
1=>null
2=>
1=>null
2=>null
3=>null //the element I was talking about above
6=>
1=>null
7=>null
到目前为止我的代码是
$projectNumber = $_GET['project_number'];
@$parentNumber = $_GET['parent_number']; //suppressed as it may not be set
$query = mysql_query("SELECT e_numbers FROM project_management WHERE project_number = '$projectNumber'");
$resultArray = mysql_fetch_assoc($query);
$eNumbers = unserialize($resultArray['e_numbers']);
if (!is_array($eNumbers)&&!isset($parentNumber)){ //first e_number assigned
$eNumbers[1] = null; //cant possibly have children so null for now
$nextENumber = 'E1';
}else{
if (!isset($parentNumber)){
$nextNumber = count($eNumbers)+1;
$eNumbers[$nextNumber] = null; //cant possibly have children so null for now
$nextENumber = 'E'.$nextNumber;
}else{
$parentIndex = explode('-', str_replace('E', '', $parentNumber));
//$nextENumber = //assign $nextENumber the incremented e number
}
}
echo $nextENumber;
//(then goes on to update sql etc etc)
这一切都很好,但对于我需要获取/分配深度数字的行。我认为这应该是某种基于 $parentIndex 和 $eNumbers 数组的递归函数,但是在递归方面我有点不够深入。
任何指向正确方向的指针都会有很大帮助。
附言
如果有更好的方法来处理增加的父/子关系,我会全力以赴。我唯一无法控制的是传入/传出数字的格式(必须是EX-Y-Z-...)
更新 我能够开发 @ircmaxell 的功能,以便在我的环境中更好地发挥作用。该函数要求您传入一个基于零的数组(可以为空)和一个可选路径。它返回新路径并更新索引数组以包含新路径。如果未找到索引,则返回错误消息。
function getNextPath(&$array, $path) { //thanks to ircmaxell @ stackoverflow for the basis of this function
$newPath = '';
$tmp =& $array;
if (is_string($path)) {
$path = explode('-', str_replace('E', '', $path));
$max = count($path);
foreach ($path as $key => $subpath) {
if (is_array($tmp)) {
if (array_key_exists($subpath, $tmp)){
$tmp =& $tmp[$subpath];
$newPath[] = $subpath;
}else{
return "Parent Path Not Found";
}
}
}
}
$tmp[] = null;
$newPath[] = count($tmp)-1;
if (count($newPath)>1){
$newPath = implode('-', $newPath);
}else{
$newPath = $newPath[0];
}
return "E".$newPath;
}
【问题讨论】:
-
"//被抑制,因为它可能没有被设置" --- 1) 什么“它”? 2)
isset -
那是 parent_number。那就是像
'E5-2-3'这样的字符串
标签: php recursion multidimensional-array