Array Intersect giving wrong output
I need to find common elements between two arrays. My code is:
$sql="SELECT DISTINCT fk_paytbl_discounts_discountid as discountid from paytbl_discounts_students WHERE fk_vtiger_cf_601='".$categoryid."'";
$discountstudentinfo=$obj开发者_运维问答db->customQuery($sql,false);
$sql1="SELECT DISTINCT fk_paytbl_discounts_discountid as discountid from paytbl_discounts_variants WHERE fk_vtiger_products_productid='".$variantid."'";
$discountvariantinfo=$objdb->customQuery($sql1,false);
$commondiscount=array_intersect($discountvariantinfo,$discountstudentinfo);
First array
Array
(
[0] => Array
(
[discountid] => 2
)
[1] => Array
(
[discountid] => 8
)
[2] => Array
(
[discountid] => 5
)
[3] => Array
(
[discountid] => 4
)
)
Second array
Array
(
[0] => Array
(
[discountid] => 1
)
[1] => Array
(
[discountid] => 5
)
)
Common array
Array
(
[0] => Array
(
[discountid] => 1
)
[1] => Array
(
[discountid] => 5
)
)
Common array should have only discountid 5 but its showing 1 also.
Please help me on this
Thanks
http://php.net/array_intersect
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
So the reason you are experiencing a problem is because, for example:
(string) array('discountid' => 5) == (string) array('discountid' => 8)
If you are running PHP 5.3, this is one solution:
$comparisonFunction = function($elem1, $elem2) {
return $elem1['discountid'] == $elem2['discountid'];
}
$commondiscount = array_uintersect(
$discountvariantinfo,
$discountstudentinfo,
$comparisonFunction
);
Prior to PHP 5.3 you could use the uglier create_function()
instead of the nifty closure. If your executing inside a method it would likely be easy to tack on a new private method to use as a callback.
If you are not using PHP 5.3 and you really don't want to use a callback, you could use the following idea:
$uniqueDiscounts = array();
foreach ($discountvariantinfo as $dvi) {
$uniqueDiscounts[$dvi['discountid']] += 1;
}
foreach ($discountstudentinfo as $dsi) {
$uniqueDiscounts[$dsi['discountid']] += 1;
}
$commondiscount = array();
foreach ($uniqueDiscounts as $ud => $count) {
if ($count == 2) {
$commondiscount[] = array('discountid' => $ud);
}
}
You will, of course, want to tidy this up or add comments to explain the algorithm.
精彩评论