Array Intersection gives incorrect 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=$objdb->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 ) ) 

Shared array

 Array ( [0] => Array ( [discountid] => 1 ) [1] => Array ( [discountid] => 5 ) ) 

The total array should only have a discount of 5, but also shows 1.

Please help me with this.

thanks

+4
source share
1 answer

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 faced with the problem is because, for example:

 (string) array('discountid' => 5) == (string) array('discountid' => 8) 

If you are using 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 a great close. If you execute inside a method, it will probably be easy to use a new private method to use as a callback.

If you are not using PHP 5.3, and you really do not want to use a callback, you can 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, of course, want to remove this or add comments to explain the algorithm.

+1
source

Source: https://habr.com/ru/post/1309739/


All Articles