Dizi yanlış çıktı vererek Kesişim

1 Cevap php

İki diziler arasında ortak öğeleri bulmak gerekir. Benim kod:

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

İlk dizi

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

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

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

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

)

İkinci dizi

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

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

)

Ortak dizi

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

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

)

Ortak dizi should have only discountid 5 but its showing 1 also.

Bana bu konuda yardımcı olun

Teşekkürler

1 Cevap

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.

Yani bir sorunla karşılaşan nedeni, örneğin, çünkü:

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

PHP 5.3 çalıştırıyorsanız, bu bir çözümdür:

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

Önce PHP 5.3 yerine şık kapağın çirkin create_function() kullanabilirsiniz. Lütfen bir yöntem içinde yürütme ise büyük olasılıkla bir geri olarak kullanmak için yeni bir özel yöntem üzerinde çakmak için kolay olurdu.

PHP 5.3 kullanmıyorsanız ve gerçekten bir geri kullanmak istemiyorsanız, size şu fikri kullanabilirsiniz:

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

Sen, elbette, bu kadar derli toplu veya algoritmasını açıklamak için yorum eklemek isteyeceksiniz.