【问题标题】:Is there a faster way to compare multiple arrays in PHP?有没有更快的方法来比较 PHP 中的多个数组?
【发布时间】:2020-02-26 13:43:23
【问题描述】:

我在比较多个数组时遇到了性能缓慢的问题。

我做的算法是:

我将首先通过 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;
        }
    }
}

所以要比较多个数组,我只使用这个 if 条件和比较符号 (==)。但我在想如果

【问题讨论】:

  • 这取决于原始数组的来源。此时可以进行此处理,而不必遍历数组并在那里检查详细信息。为了提高性能,尽可能减少数据库调用的次数通常会更快。
  • 这段代码的最佳解决方案是删除它,因为它什么都不做。

标签: php laravel optimization


【解决方案1】:

不要循环查询数据库,可以使用 array_column 将分支数组导出到“userId”和“userBranchId”列 最后使用“whereIn”构建查询

【讨论】:

    【解决方案2】:

    我同意@thaiha,您可以将查询减少到一个,然后对数组进行比较。例如在 Mysql 中你可以做类似的事情。

    select * from `permissions` where (`user_id `, `branch_id `) in (('1', '2'), ('2', '4'));
    

    然后为了比较数组,你可以做你的循环,或者使用一个 php 函数来比较数组,比如 array_diff 你期望所有的都匹配一组特定的权限。或者类似的东西。

    【讨论】:

      【解决方案3】:

      而不是循环数组。我建议改用急切加载。

      分支模型

      public function permissions(){
       return $this->hasMany('App\Permission', 'foreign_key', 'local_key');
      }
      

      在你的控制器中

      Branch::with('permissions')->where($condition)->get();
      

      在此处阅读文档:https://laravel.com/docs/6.x/eloquent-relationships

      【讨论】:

        猜你喜欢
        • 2014-07-22
        • 1970-01-01
        • 2023-04-10
        • 2014-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-17
        相关资源
        最近更新 更多