Compare multidimensional arrays in PHP
The simplest way I know:
$a == $b;
Note that you can also use the ===
. The difference between them is:
With Double equals
==
, order is important:$a = array(0 => 'a', 1 => 'b');
$b = array(1 => 'b', 0 => 'a');
var_dump($a == $b); // true
var_dump($a === $b); // falseWith Triple equals
===
, types matter:$a = array(0, 1);
$b = array('0', '1');
var_dump($a == $b); // true
var_dump($a === $b); // false
Reference: Array operators
Compare multidimensional array values by key in php
I need compare values of the products by each key. To highlight rows
in the compare table where price, quantity, availability, or
manufacturer is different.
If you want to highlight all products unless all of them have exactly the same price, quantity, availability, or manufacturer.
function:
function productsIdentical(array &$products) : bool
{
if (count($products) < 2) {
throw new \InvalidArgumentException("You should pass at least 2 products to compare");
}
$compare = '';
foreach ($products as $product) {
ksort($product); //to make comparison of key order insensitive
$sha = sha1(json_encode($product));
if (empty($compare)) {
$compare = $sha;
} elseif ($sha !== $compare) {
return false;
}
}
return true;
}
returns true
only if all products' fields have exactly the same keys and value, otherwise it returns false
so you use it this way:
$identicalFlag = productsIdentical($all_products);
if ($identicalFlag === false) {
echo "Products are not identical:" . PHP_EOL;
$nonIdenticalProductsArr = array_keys($all_products);
echo "Non identical products are:" . PHP_EOL;
print_r($nonIdenticalProductsArr);
//do your styling on $nonIdenticalProducts
} else {
echo "Products are identical" . PHP_EOL;
}
Output:
for identical products:
Products are identical
for non identical:
Products are not identical:
Non identical products are:
Array
(
[0] => product_1
[1] => product_2
[2] => product_3
)
Or if you want to detect every product field that is not the same across all products in the array use this function:
function getFieldsNonIdentical(array &$products) : array
{
if (count($products) < 2) {
throw new \InvalidArgumentException("You should pass at least 2 products to compare");
}
$compareArr = [];
$keyDifferentArr = [];
foreach ($products as $product) {
foreach($product as $key => $val) {
if (!key_exists($key, $compareArr)) {
$compareArr[$key] = $val;
} elseif ($compareArr[$key] !== $val) {
$keyDifferentArr[$key] = true;
}
}
}
return array_keys($keyDifferentArr);
}
this way:
$fieldsNonIdentical = getFieldsNonIdentical($all_products);
if (!empty($fieldsNonIdentical)) {
echo "Fields that are non identical:" . PHP_EOL;
print_r($fieldsNonIdentical);
//do your styling
$nonIdenticalStyle = 'style="background-color: lightblue;"';
$styleArr = [];
foreach ($fieldsNonIdentical as $key => $value) {
$styleArr[$value] = $nonIdenticalStyle;
}
echo "Non Identical fields styling is:" . PHP_EOL;
print_r($styleArr);
} else {
echo "All fields in all products are the same." . PHP_EOL;
}
Output
for identical:
All fields in all products are the same.
for non identical:
Fields that are non identical:
Array
(
[0] => price
[1] => manufacturer
)
Non Identical fields styling is:
Array
(
[price] => style="background-color: lightblue;"
[manufacturer] => style="background-color: lightblue;"
)
PHP Compare two multidimensional arrays by key and value
function calculateDifference($array1, $array2){
$difference = array();
foreach($array1 as $key => $value){
if(isset($array2[$key])){
$difference[$key] = abs($array1[$key] - $array2[$key]);
}else{
$difference[$key] = $value;
}
}
foreach($array2 as $key => $value){
if(isset($array1[$key])){
$difference[$key] = abs($array1[$key] - $array2[$key]);
}else{
$difference[$key] = $value;
}
}
return $difference;
}
PHP Compare two multidimensional arrays
Assuming that $guestArr
is your guest array and $secondArr
is your second array, the solution would be like this:
foreach($secondArr as $key => $arr){
if(!in_array($arr['guest_allow'], $guestArr)){
unset($secondArr[$key]);
}
}
// display $secondArr array
var_dump($secondArr);
Here's the live demo.
Compare multidimensional array with another array in PHP and get the values from the multidimensional array
For your example data, you could use array_reduce and use in_array to check if the tag
is present in $compare_array
If you must make a variable with the name from the $compare_array
and append the value to the variable you might use extract with a flag that suits your expectations.
The value
is not present in all the example data so you might also check if that exists.
$compare_array = array('DOCUMENT', 'SENDERID', 'SENDERSHORTNAME', 'RECIPIENTID');
$result = array_reduce($arrays, function($carry, $item) use ($compare_array) {
if(isset($item["value"]) && in_array($item["tag"], $compare_array, true)) {
$carry[$item["tag"]] = $item["value"];
}
return $carry;
});
extract($result, EXTR_OVERWRITE);
echo $SENDERID;
echo $RECIPIENTID;
Demo
Compare two multidimensional array and replace values based on matching keys
This can be a one-character change:
foreach ($array1 as $defArr)
goes to
foreach ($array1 as &$defArr)
# ^
The &
reference operator points to the original sub array in the foreach
loop context rather than a temporary variable.
However, it's a bit safer to use the index explicitly:
foreach ($array1 as $i => $defArr) {
foreach ($array2 as $j => $dayArr) {
if ($dayArr['_id'] == $defArr['_id']) {
$array1[$i]['M'] = $array2[$j]['M'];
$array1[$i]['F'] = $array2[$j]['F'];
}
}
}
If speed is important or $array2
is large, the time complexity of your algorithm is O(n * m). I recommend hashing $array2
for fast lookups as follows (O(n)):
$lookup = array_reduce($array2, function ($a, $e) {
$a[$e['_id']] = $e;
return $a;
});
foreach ($array1 as $i => $e) {
if (array_key_exists($e['_id'], $lookup)) {
$array1[$i]['M'] = $lookup[$e['_id']]['M'];
$array1[$i]['F'] = $lookup[$e['_id']]['F'];
}
}
Try it!
multidimensional array difference php
Please check if I understand you correctly then this code snippet can help to you solve your problem. I have tested it for your specified problem only. if there are other testcases for which you want to run this, you can tell me to adjust the code.
$a1 = array(
'a1' => array('a_name' => 'aaa', 'a_value' => 'aaaaa'),
'b1' => array('b_name' => 'bbb', 'b_value' => 'bbbbbb'),
'c1' => array('c_name' => 'ccc', 'c_value' => 'cccccc')
);
$a2 = array(
'b1' => array('b_name' => 'zzzzz'),
);
$result = check_diff_multi($a1, $a2);
print '<pre>';
print_r($result);
print '</pre>';
function check_diff_multi($array1, $array2){
$result = array();
foreach($array1 as $key => $val) {
if(isset($array2[$key])){
if(is_array($val) && $array2[$key]){
$result[$key] = check_diff_multi($val, $array2[$key]);
}
} else {
$result[$key] = $val;
}
}
return $result;
}
EDIT: added tweak to code.
Compare multidimensional arrays with array_diff
You could use array_udiff.
If will filter the first array, by comparing its elements to the elements of other arrays passed to array_udiff
using the given callback. When the callback returns 0
for a pair, that element is removed from the result.
$result = array_udiff($arr2, $arr1, function ($a, $b) {
return strcmp($a['email'], $b['email']);
});
Compare two multidimensional arrays then create array of only unique
I would just do a nested foreach loop. I don't know which programming language You're using, but assuming that it's PHP ($):
$tmpArray = array();
foreach($newData as $data1) {
$duplicate = false;
foreach($oldData as $data2) {
if($data1['id'] === $data2['id'] && $data1['name'] === $data2['name'] && $data1['sex'] === $data2['sex']) $duplicate = true;
}
if($duplicate === false) $tmpArray[] = $data1;
}
You then have the desired array in the $tmpArray
variable. You can make of course $newData = $tmpArray;
afterwards.
PHP compare two dimension array
foreach($array1 as $k1 => $arrays) {
foreach($arrays as $k2 => $val) {
if($array2[$k1][$k2] == $val) {
// $array1[$k1][$k2] is equal to $array2[$k1][$k2]
}
}
} // end of foreach
The foreach($a as $k => $v)
syntax does the same thing as foreach($a as $v)
, except that it also puts the key associated with the value into $k
.
Related Topics
How to Get the Client's Ip Address in a PHP Webservice
Sum Values in Foreach Loop PHP
How to Capture PHP Output into a Variable
File_Get_Contents Returns 403 Forbidden
Destroy or Unset Session When User Close the Browser Without Clicking on Logout
Mysql_Real_Escape_String VS Addslashes
How to Sort an Array of Utf-8 Strings
Instantiate a Class with or Without Parentheses
Can You Add an If Statement in Order By
How to Use Curl Instead of File_Get_Contents
Convert PDF to Jpeg with PHP and Imagemagick
How to Add Text to an Image with PHP Gd Library
Call Laravel Controller via Command Line
PHP Failed to Open Stream: Is a Directory