下面是一個通過PHP遞歸函數實現權限樹檢查的示例代碼:
<?php
// 定義權限樹結構
$permissions = array(
'user' => array(
'create' => true,
'read' => true,
'update' => true,
'delete' => true
),
'post' => array(
'create' => true,
'read' => true,
'update' => false,
'delete' => false
),
'comment' => array(
'create' => true,
'read' => true,
'update' => false,
'delete' => false
)
);
// 定義用戶權限
$userPermissions = array(
'user' => array(
'create' => true,
'read' => true,
'update' => true,
'delete' => false
),
'post' => array(
'create' => true,
'read' => true,
'update' => false,
'delete' => false
)
);
// 遞歸檢查權限
function checkPermission($permissions, $userPermissions)
{
foreach ($permissions as $key => $value) {
if (is_array($value)) {
checkPermission($value, $userPermissions[$key]);
} else {
if ($value !== $userPermissions[$key]) {
echo "權限不足:$key/$value\n";
}
}
}
}
// 檢查權限
checkPermission($permissions, $userPermissions);
?>
在這個示例中,我們首先定義了一個權限樹結構 $permissions
和一個用戶權限 $userPermissions
。然后定義了一個遞歸函數 checkPermission
來逐層檢查權限樹和用戶權限是否匹配。最后調用 checkPermission
函數來檢查權限。如果權限不匹配,則輸出提示信息。
請根據實際情況調整權限樹和用戶權限,并根據需要修改遞歸函數中的邏輯。