gpt4 book ai didi

php - 数组相交给出错误的输出

转载 作者:可可西里 更新时间:2023-10-31 23:44:19 27 4
gpt4 key购买 nike

我需要找到两个数组之间的公共(public)元素。我的代码是:

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

第一个数组

Array
(
[0] => Array
(
[discountid] => 2
)

[1] => Array
(
[discountid] => 8
)

[2] => Array
(
[discountid] => 5
)

[3] => Array
(
[discountid] => 4
)

)

第二个数组

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

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

)

普通数组

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

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

)

普通数组应该只有 discountid 5 但它也显示 1。

请帮帮我

谢谢

最佳答案

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.

所以您遇到问题的原因是,例如:

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

如果您运行的是 PHP 5.3,这是一种解决方案:

$comparisonFunction = function($elem1, $elem2) {
return $elem1['discountid'] == $elem2['discountid'];
}
$commondiscount = array_uintersect(
$discountvariantinfo,
$discountstudentinfo,
$comparisonFunction
);

在 PHP 5.3 之前,您可以使用更丑陋的 create_function() 而不是漂亮的闭包。如果您在一个方法中执行,那么添加一个新的私有(private)方法以用作回调可能会很容易。

如果您没有使用 PHP 5.3 并且您真的不想使用回调,您可以使用以下想法:

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

当然,您会想要整理它或添加评论来解释算法。

关于php - 数组相交给出错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2832208/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com