简体   繁体   中英

find difference between two associative multidimensional arrays

I have two associative multidimensional arrays, now I want to get values which are not present in the second array (compare by both key name and type).

$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']));
}

Output :

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']));
}

Output :

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

I don't know how to find difference Result :

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

You can use array_diff_assoc php function to find difference or value that is not present in array. Example:

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

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

Example output:

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

There is a function array_diff_assoc() for example:

<?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);
?>

You can try above code here

And you can use array_intersect() for find resemblance.for example:

<?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);
?>

You can try above code here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM