文章目錄
- 1 變量定義
- 2. 核心特性
- code
1 變量定義
- 類型:嵌套的關聯數組(Nested Associative Array)
- 外層結構:[中繼ID => 賬號列表]
- 鍵 (Key):中繼ID(字符串或整型)
- 值 (Value):索引數組(包含屬于該中繼的所有SIP賬號字符串)
內存形態:
php
[
“中繼ID_A” => [“賬號1”, “賬號2”, …],
“中繼ID_B” => [“賬號X”, “賬號Y”, …]
]
數據結構存儲
// 初始狀態
$existingAccounts = [
“2” => [“1001”],
“5” => [“2001”]
];
// 添加新賬號到中繼2
$existingAccounts[“2”][] = “1002”;
// 添加新中繼組
$existingAccounts[“9”] = [“3001”];
// 最終形態
[
“2” => [“1001”, “1002”],
“5” => [“2001”],
“9” => [“3001”]
]
2. 核心特性
特性 | 說明 |
---|---|
按中繼分組 | 以中繼ID為分組維度,天然隔離不同中繼的賬號 |
值唯一性 | 同一中繼組內SIP賬號強制唯一(通過數組值隱式保證) |
O(1)快速檢索 | 通過isset($existingAccounts[$trunkIdx]) 可瞬間判斷中繼是否存在 |
O(n)成員檢查 | 通過in_array($account, $existingAccounts[$trunkIdx]) 檢查賬號重復性 |
in_array解析:
$needle:要搜索的值(示例中的 SIP 賬號)
$haystack:被搜索的數組(示例中的 $existingAccounts[$trunkIdx])
bool in_array(mixed $needle, array $haystack [, bool $strict = false])
code
1 基礎功能:賬號添加
// 檢查中繼組是否存在
if (!isset($existingAccounts[$trunkIdx])) {// 新建中繼分組(初始化空數組)$existingAccounts[$trunkIdx] = [];
}// 添加賬號到中繼組
$existingAccounts[$trunkIdx][] = $account;
2 去重高效性 ,添加新賬號時,只需兩步驗證
$trunkIdx = "2"; // 目標中繼
$newAccount = "1002";if (isset($existingAccounts[$trunkIdx]) && in_array($newAccount, $existingAccounts[$trunkIdx])) {// 賬號已存在 → 拒絕添加
} else {// 安全添加賬號
}
3 函數封裝
// 新增賬號時防重復檢查
function addAccount($trunkIdx, $account) {global $existingAccounts;if (isset($existingAccounts[$trunkIdx]) {if (in_array($account, $existingAccounts[$trunkIdx])) {throw new Exception("賬號 $account 已存在于中繼 $trunkIdx");}} else {$existingAccounts[$trunkIdx] = []; // 初始化新中繼組}// 安全添加賬號$existingAccounts[$trunkIdx][] = $account;
}// 示例:添加重復賬號(觸發異常)
addAccount("2", "1001"); // 拋出異常:賬號1001已存在于中繼2