PHP优化嵌套循环

时间:2015-09-12 10:24:54

标签: php loops foreach nested

我有一系列匹配项,每个匹配项都有一个ID和一组用户(从2到4),每个用户都由它自己的user_id唯一标识。数组示例:

array (size=2)
  0 => 
    array (size=2)
      'id' => int 11268
      'users' => 
        array (size=2)
          0 => 
            array (size=1)
              'user_id' => int 960781
          1 => 
            array (size=1)
              'user_id' => int 960786
  1 => 
    array (size=2)
      'id' => int 11267
      'users' => 
        array (size=2)
          0 => 
            array (size=1)
              'user_id' => int 960783
          1 => 
            array (size=1)
              'user_id' => int 902177

现在我想将用户详细信息添加到上面的数组中,所以我对数据库进行了查询,我得到了:( id = n的行包含user_id = n的用户的详细信息)

if ($res = $stmt->get_result()) { // it gets user details
    while($row=$res->fetch_assoc()) {
        foreach ($matches as &$match) {
            foreach ($match['users'] as &$user) {
                if($user['user_id']==$row['id']) {
                    $user['details']=$row;
                }
            }
        }
    }
}

这工作正常,但这不是最好的方法,因为对于每一行我都走完所有阵列。你知道如何优化它吗?

非常感谢

2 个答案:

答案 0 :(得分:1)

您可以通过userid索引用户数组来简化问题。代码现在变得有点复杂,但计算复杂度级别更低。如果新解决方案真的更快取决于各个阵列的实际大小,那么您必须使用真实生产数据来测量这两个解决方案,以查看实际上最快的解决方案。

<?php

function index_array_by($array, $key) {
    $result = array();
    foreach($array as &$value) {
        $new_key = $value[$key];
        $result[$new_key] = &$value;
    }
    return $result;
}

foreach($matches as &$match) {
    $match['users'] = index_array_by($match['users'], "user_id");
}

if ($res = $stmt->get_result()) { // it gets user details
    while($row=$res->fetch_assoc()) {
        foreach ($matches as &$match) {
            $user_id = $row['id'];
            $match['users'][$user_id]['details'] = $row;
        }
    }
}

?>

答案 1 :(得分:0)

我发现这个解决方案只需扫描一次数组,但我猜它会占用更多内存,因为我将行保存到数组中:

//Save the results in an array to later add to the matches array
            if ($res = $stmt->get_result()) { //second get: it gets user details
                while($row=$res->fetch_assoc()) {
                    $rows[$row['id']]=$row;
                }
            }
            mysqli_free_result($res);
            //Add the user details to the matches array
            foreach ($matches as &$match) {
                foreach ($match['users'] as &$user) {
                    $user['details']=$rows[$user['user_id']];
                }
            }