douxiaqin2062 2015-01-17 12:21
浏览 41
已采纳

如何在索引不匹配时比较两个数组

I've got two mySQL queries which pull data from my database. Without going into too much detail, after running the queries the results of both should be related when assigning to an array (i.e. array1[x] and array2[x] should be related by the x offset by virtue of the nature of the sql queries).

However this isn't robust enough if something happens where one of the queries returns less or more than the other, then the offset will be off making my for loop comparison (at the end of the code snippet below) faulty.

['companyid'] in both arrays is fixed and will not change, so is there a way of making that the index of the arrays and looping through it for comparison instead? Note that ['companyid'] can be any non-sequential number.

*SQL Query*

         while ($row = $result->fetch()) {  
            $pastcompanies[] = array(
                    'companyid' => $row['id'],
                    'name' => $row['name'],
                    'contactid' => $row['contactid'],
                    'firstname' => $row['firstname'],
                    'lastname' => $row['lastname'],
                    'email' => $row['email']        
   );
        }   

*SQL Query*

         while ($row = $result->fetch()) {  
            $nowcompanies[] = array(
                    'companyid' => $row['id'],
                    'name' => $row['name'],
                    'contactid' => $row['contactid'],
                    'firstname' => $row['firstname'],
                    'lastname' => $row['lastname'],
                    'email' => $row['email']        
    );
        }   

        for ($x=0;$x<count($pastcompanies);$x++){
                if ($pastcompanies[$x]['contactid']!=$nowcompanies[$x]['contactid']){
                     echo $pastcompanies[$x]['firstname']." has been replaced by "
                     .$nowcompanies[$x]['firstname']; 
                }
        }       
  • 写回答

1条回答 默认 最新

  • duanhuang4841 2015-01-17 12:29
    关注

    Comparison on array is slow, unnecessary and insecure compared to a database query doing the comparison. A query using join to compare two tables is more robust.

    SELECT * FROM companies c
    JOIN past_companies pc 
    ON pc.companyid = c.companyid
    WHERE pc.contactid != c.contactid;
    

    This code above should give you a result set where all the first names aren't the same as before. Thus eliminating the need to compare arrays on php. Please not that this code is just a sample to how a comparison can be done on the database.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算