将 PHP 中的两个二维数组与 array_diff 错误进行比较

Compare two 2-dimension arrays in PHP with array_diff error

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

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

如果同一日期的两个 table 中的数字不相同,我将打印 "date, number from table 1 - number from table 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

table 有两个维度

函数array_diff只检查一维数组,这来自php手册

This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);.

通过这个link

您可以迭代数组并比较每个一维数组。

this可能对你有帮助

array_diff 功能没问题,我认为问题出在$result_one$result_two。打印出来看看里面有什么。

您可以使用单个 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']);
}