找出两个关联多维数组之间的差异

时间:2017-07-16 09:59:13

标签: php associative-array

我有两个关联的多维数组,现在我想得到第二个数组中不存在的值(按键名和类型进行比较)。

$sql = "select * from `medicine`;"; 
$result = mysqli_query($con, $sql);
$response = array();
while ($row = mysqli_fetch_array($result)) {
    array_push($response, array("name" => ucfirst($row['name']), "type" => $row['type']));
}

输出:

  

Array ( [0] => Array ( [name] => A2 [type] => syringe ) [1] => Array ( [name] => A3 [type] => syringe ) [2] => Array ( [name] => A3 [type] => capsule ) [3] => Array ( [name] => A4 [type] => syringe )[4] => Array ( [name] => A5 [type] => a ) [5] => Array ( [name] => A6 [type] => capsule ) )

$s = "select * from `doctor_medicine` where `email` = '$email';";   
$res = mysqli_query($con, $s);
$resp = array();
while ($row = mysqli_fetch_array($res)) {
    array_push($resp, array("name" => ucfirst($row['medicine_name']),"type" => $row['type']));
}

输出:

  

Array ( [0] => Array ( [name] => A2 [type] => syringe ) [1] => Array ( [name] => A3 [type] => capsule ) [2] => Array ( [name] => A4 [type] => syringe ) )

我不知道如何找到差异 结果:

  

Array ( [0] => Array ( [name] => A3 [type] => capsule ) [4] => Array ( [name] => A5 [type] => a ) [5] => Array ( [name] => A6 [type] => capsule ) )

2 个答案:

答案 0 :(得分:1)

您可以使用 array_diff_assoc php函数来查找数组中不存在的差异或值。 示例:

$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");

$result = array_diff_assoc($array1, $array2);
print_r($result);

示例输出:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

答案 1 :(得分:1)

有一个函数array_diff_assoc() 例如:

<?php
$a = array(
   "who" => "you", 
   "what" => "thing", 
   "where" => "place",
   "when" => "hour"
);

$b = array(
   "when" => "time", 
   "where" => "place", 
   "who" => "you",
   "what" => "thing"
);

$c = array_diff_assoc($a, $b);
print_r ($c);
?>

您可以尝试上面的代码here

您可以使用array_intersect()查找相似内容。例如:

<?php
$a = array(
  "who" => "you", 
  "what" => "thing", 
  "where" => "place",
  "when" => "hour"
);
$b = array(
  "when" => "time", 
  "where" => "place", 
  "who" => "you",
  "what" => "thing"
);
$c = array_intersect($a, $b);
print_r ($c);
?>

您可以尝试上面的代码here