Reputation: 14436
I have two associative arrays:
ArrayA = array( [10] => ten
[12] => twelve
[22] => 10
[30] => 10, 12, 8
)
ArrayB = array( [10] => net
[12] => evlewt
[22] => 11, 12, 10
[30] => 10
)
The values of same keys on both arrays need to be compared. Some keys have CSV values and that can be on both the arrays.
For instance, [22]
on ArrayA
should be checked in CSV on ArrayB
. Likewise, [30]
in ArrayB
should be checked in CSV on ArrayA
. Others should be compared as usual ==
Note: I am trying to avoid a looping here. We can certainly do this in multiple ways with Loop. I am wondering if there is a quick and efficient way to do this without looping.
Edit: To clarify further, this is how these two should be compared:
Is "ten" in ArrayA == "net" in ArrayB?
Is "twelve" in ArrayA == "evlewt" in ArrayB?
Is 10 in ArrayA existing in (11, 12, 10) of ArrayB?
Is (10, 12, 8) of ArrayA containing the 10 ArrayB?
Upvotes: 1
Views: 270
Reputation: 603
I hope I understand the question correctly. If you normalize the data first you can just compare the arrays
For instance:
$a = array(
10 => 'net',
12 => 'evlewt',
22 => '10,12,11',
30 => '12,10'
);
$b = array(
10 => 'net',
12 => 'evlewt',
22 => '11,12,10',
30 => '12,10'
);
function normalize(&$value, $key) {
$value = explode(',', $value);
sort($value);
$value = implode(',', $value);
}
array_walk($a, 'normalize');
array_walk($b, 'normalize');
var_dump($a == $b); // outputs true
EDIT: In order to evaluate two arrays by whether an element in either array is a subset of another, I would normalize values to array and use the reduce_array()
function.
<?php
$a = array(
10 => 'net',
12 => 'evlew',
22 => '10,12,11',
30 => '12,10,11'
);
$b = array(
10 => 'net',
12 => 'evlewt',
22 => '11,12,10',
30 => '12,10'
);
function normalize(&$value, $key) {
$value = explode(',', $value);
}
function compare_value($v, $w) {
if (false === $v) return false;
global $a, $b;
if(is_subset($a[$w], $b[$w]) || is_subset($b[$w], $a[$w]))
return true;
return false;
}
function is_subset($needle, $haystack) {
return count(array_intersect($needle, $haystack)) === count($needle);
}
array_walk($a, 'normalize');
array_walk($b, 'normalize');
$result = array_reduce(array_keys($a), 'compare_value', true);
var_dump($result); // outputs false
$a = array(
10 => 'net',
12 => 'evlewt',
22 => '10',
30 => '12,10,11'
);
$b = array(
10 => 'net',
12 => 'evlewt',
22 => '11,12,10',
30 => '12,10'
);
array_walk($a, 'normalize');
array_walk($b, 'normalize');
$result = array_reduce(array_keys($a), 'compare_value', true);
var_dump($result); // outputs true
Upvotes: 2