在比较多个阵列时,我遇到了性能下降的问题。
我制定的算法是:
我将首先通过foreach循环数组
foreach($branches as $index => $branch) {
if (!$identical) {
continue;
}
// Basically this $permissions will be fetching data from the database.
$permissions = $this->get()
->where('user_id', $userId)
->where('branch_id', $userBranchId)
->sortBy('permission_id')
->pluck(['permission_id']);
// if index = 0 then I'll initialize the temporary variable (ARRAY) $initial otherwise I'll compare two variable (ARRAY)
if ($index === 0) {
$initial = $permissions;
} else {
if ($initial != $permissions) {
$identical = false;
}
}
}
因此,为了比较多个数组,如果条件和比较符号(==),则仅使用此数组。但是我在想
答案 0 :(得分:0)
不要循环查询数据库,可以使用array_column将分支数组导出到“ userId”和“ userBranchId”列 使用“ whereIn”完成构建查询
答案 1 :(得分:0)
我同意@thaiha,您可以将查询减少到仅一个,然后对数组进行比较。例如,在Mysql中,您可以执行类似的操作。
select * from `permissions` where (`user_id `, `branch_id `) in (('1', '2'), ('2', '4'));
然后用于比较数组,您可以执行循环,或使用php函数之一比较数组,例如array_diff,如果您希望它们都与特定的权限集匹配。或类似的东西。
答案 2 :(得分:0)
代替循环数组。我建议改用急切加载。
分支模型
public function permissions(){
return $this->hasMany('App\Permission', 'foreign_key', 'local_key');
}
和您的控制器中
Branch::with('permissions')->where($condition)->get();