如何使用具有两个元素的数组在php中获得数组差异

时间:2017-05-28 19:07:01

标签: php arrays

所以,我有两个查询将从数据库中提取数据。但是,我需要使用这些数据来使用php获取数组差异。我想将employeeName和names发送到一个数组中,然后得到差异。我使用的以下代码无法按预期工作。对此事有任何解决方案吗?

<?php

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include_once 'config.php';

$sql1 = "SELECT employeeName, designation FROM t2o_mappings WHERE type = '". $_GET['type'] ."' AND employeeCompany = '".$_GET['employeeCompany']."'"; //System Data;
$sql2 = "SELECT employeeName, designation FROM mappings_view WHERE uNo = '" . $_GET['uNo'] . "' AND uCompany = '" . $_GET['uCompany'] . "' AND type = '". $_GET['type'] ."' AND employeeCompany = '".$_GET['employeeCompany']."'"; //App Data;
//WHERE uNo = '".$_GET['uNo']."' AND uCompany = '".$_GET['uCompany']."'

$result1 = sqlsrv_query($conn, $sql1);
$result2 = sqlsrv_query($conn, $sql2);

$row1 = [];
$row2 = [];

while ($rs1 = sqlsrv_fetch_array($result1, SQLSRV_FETCH_ASSOC)) {

    $row1[] = $rs1['employeeName, designation'];
}

while ($rs2 = sqlsrv_fetch_array($result2, SQLSRV_FETCH_ASSOC)) {

    $row2[] = $rs2['employeeName, designation'];
}

print_r($row1);
print_r($row2);

$HaveSysNoApp = array_diff($row1, $row2);  //Have in System, Not in App
$HaveAppNoSys = array_diff($row2, $row1); //Have in App, Not in System

echo 'HaveSysNoApp';
print_r($HaveSysNoApp);
echo '$HaveAppNoSys';
print_r($HaveAppNoSys);

?>

2 个答案:

答案 0 :(得分:2)

这里有语法问题

$row1[] = $rs1['employeeName, designation'];

正确的方法是:

$row1[] = [
    $rs1['employeeName'],
    $rs1['designation']
];

但是array_diff()会将通知“数组转换为字符串转换”,因为它只能处理一个维度。 The PHP array_diff() documentation contains this note

  

注意:

     

当且仅当(字符串)$ elem1 ===(字符串)$ elem2时,两个元素被认为是相等的。换句话说:当字符串表示相同时。

由于您要比较多维数组,因此可以使用array_filter()函数。

例如:

$HaveSysNoApp = array_filter($row1, function ($item) use ($row2) {
    return !in_array($item, $row2);
});

答案 1 :(得分:0)

您可以使用此查询直接在数据库中执行此操作(相反的检查将类似):

SELECT system.employeeName, system.designation
FROM t2o_mappings AS system
WHERE system.type = ?
  AND system.employeeCompany = ?
  AND NOT EXISTS (
    SELECT NULL
    FROM mappings_view AS app
    WHERE app.employeeName = system.employeeName
      AND app.designation = system.designation
      AND app.type = system.type
      AND app.uNo = ?
      AND app.uCompany = ?
  )

这些问号使其成为参数化查询,这会阻止SQL注入(参数值不是查询的一部分,因此它们无法更改其含义)。您可以使用其他参数数组调用它(顺序必须匹配):

$params = [
    $_GET['type'],
    $_GET['employeeCompany'],
    $_GET['uNo'],
    $_GET['uCompany']
];
$haveSysNoAppResult = sqlsrv_query($conn, $sql, $params);