php—逐键查找两行数据之间的差异

9w11ddsr  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(357)

我有两行数据-总是只有两行,但最多可能有40列左右。列名因具体情况而异,但下面是一个具有代表性的示例:

id | height | width | colour | in_stock | featured | on_sale
------------------------------------------------------------
1  |  30    |  20   |  black | yes      | no       |  yes
2  |  30    |  25   |  red   | yes      | yes      |  no

我想把这两行之间的所有差异放到一个数组中,这样我就可以记录从第1行到第2行的变化。
我以为它能胜任这项工作!
所以我兴高采烈地扔了array_diff(),这样:

//Simplified queries for the example

$sql1 = "SELECT * FROM table WHERE id = 1";
$rs1     = $conn->Execute($sql1);
$rs1     = $rs1->fields;

$sql2  = "SELECT * FROM table WHERE id = 2";
$rs2      = $conn->Execute($sql2);
$rs2      = $rs2->fields;

//Build first array
foreach($rs1 as $key => $value){
  $data1[$key] = $value;
}

//Build second array
foreach($rs2 as $key => $value){
  $data2[$key] = $value;
}

//Find the differences
$theDifferences = array_diff($data1, $data2);

//Loop through the differences logging the changes
foreach($theDifferences as $field => $value){
 echo "Change found for ".$field."!";
}

为什么那不管用。
这个“看起来”很有效。由于许多列包含长字符串、颜色名称、日期等,因此当其中一个列发生更改时,它会被适时地推送到differences数组中。问题是(当然)多个“yes”或“no”列的行为与我预期的不同。因此,对于表格示例,上面代码的结果是:

colour, width

因为data1数组和data2数组都包含no和yes,所以不能“看到”featured或on-sale列发生了更改。
我想我需要逐项比较?类似于array_diff_key()的反义词?但我被困在这里了。
我还考虑了是否可以只使用sql查询来实现这一点,我认为这样效率更高,但这远远超出了我的sql能力。
提前谢谢。

oxosxuxt

oxosxuxt1#

我想你就快到了。在你询问之后,也许会这样:

$theDifferences = array();
foreach($rs1 as $key => $value){
   if ($rs2[$key] != $value){
      $theDifferences[$key] = $value;
   }
}

至于sql,您可以使用except来获取两个查询之间不同的行列表,但是您仍然需要循环遍历键并查找空值—这并不能节省很多时间。

相关问题