我有一個處理另一頁上父/子元素命名的腳本。這個名字的格式就像E5-2-3
,它代表了第五個元素的第二個孩子的第三個孩子。PHP - 基於索引位置的遞增數組
我需要做的是將父名稱傳遞給該函數並返回下一個子項的名稱。該值將是最後一個孩子的增量,如果是第一個孩子,則該值爲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
數組的某種遞歸函數,但是當涉及遞歸時,我有點超出了我的深度。
任何正確的方向指針將是一個很大的幫助。
PS 如果有更好的方法來處理遞增的父母/子女關係,我全是耳朵。在我的掌握的唯一的事情是正在傳遞的數字的格式輸入/輸出(必須是EX-Y-Z-...
)
UPDATE我才得以發展@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` – zerkms 2011-02-11 03:33:27
這就是parent_number。這就是'E5-2-3'這個字符串' – 2011-02-11 03:35:35