php - 比较 PHP 中的两个二维数组与 array_diff 错误

标签 php mysql arrays compare array-difference

问题可能有所不同,例如:比较 mySQL 中的两个表的特定指标。我的表有一个维度(日期)和一个指标(数字),我想检查我是否在同一日期获得相同的数字。

作为解决方案,我开始创建一个 PHP 脚本,其中表内容将被放入数组中。然后我比较这个数组来追踪差异。

如果相同日期的两个表中的数字不相同,我将打印“日期,表 1 中的数字 - 表 2 中的数字”。

这是我的代码,但似乎我遇到了 array_diff 问题:

// Connect to the database (mySQL)
$Db = mysqli_init();
$Db->options(MYSQLI_OPT_LOCAL_INFILE, true);
$Db->real_connect($servername, $username, $password, $dbname, 3306);

// Creation of 1st Array
$result_one  = array();

// Creation of 1st SQL query
$sql = "select date, sum(number) from Table1 group by date";

// Run the 1st query
$query = $Db->query($sql);

// Save the results of the 1st query in the 1st array called result_one
$i = 0;
while ($row = $query->fetch_assoc()) 
{
    echo "aaa";
    $result_one[$i] = $row;
    $i++;
}

// Print the results (array)
print_r ($result_one);

#####################################################

// Creation of 2nd Array
$result_two  = array();

// Creation of 1st SQL query
$sql = "select date, sum(number) from Table2 group by date";

// Run the 1st query
$query = $Db->query($sql);

// Save the results of the 1st query in the 1st array called result_two
$i = 0;
while ($row = $query->fetch_assoc()) 
{
    echo "aaa";
    $result_two[$i] = $row;
    $i++;
}

// Print the result_two (array)
print_r ($result_two);

#####################################################

// Use of array_diff
$diff = array_diff($result_one,$result_two);

// Print the differences
print_r($diff);

我收到类似这样的错误:

PHP Stack trace:... Array to string conversion

表格有两个维度

最佳答案

您可以使用单个 SQL 查询执行此操作:

$sql = "SELECT t1.date, t1.number as `t1num`, 
        t2.number as `t2num` 
        FROM `table1` t1, `table2` t2 
        WHERE t1.date = t2.date AND t1.number != t2.number"
$query = $Db->query($sql);


while ($row = $query->fetch_assoc()) 
{
    echo sprintf("mismatch: date: %s, table1: %s, table2: %s", $row['date'], $row['t1num'], $row['t2num']);
}

关于php - 比较 PHP 中的两个二维数组与 array_diff 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34204979/

相关文章:

PHP 与多服务器

php - 帮助进行 MySQL 查询

java - mysql workbench 中的奇怪密码类型

arrays - 尝试以算术调用数组变量时出错

c - 根据空格划分 char 数组中的字符

php - PDO - 查询不返回结果

php - 获取当前文件 PHP 的父文件夹

php - 在 Linux 中找不到 fatal error COM 类

php - MYSQL 列指定两次 INSERT

arrays - 如何根据与特定键的相似性对字符串数组进行排序