Re: array_intersect problem

From: Date: Tue, 26 Dec 2006 04:47:33 +0000
Subject: Re: array_intersect problem
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-246219@lists.php.net to get a copy of this message
2006/12/25, Leo Liu <kkl_sg@yahoo.com>:
Hi, I try to intersect associative array and it seems to fail to do so. Can anyone show me a walk around? For example I have array1 Array (
    [0] => Array
        (
            [imageID] => 1
        )
    [1] => Array
        (
            [imageID] => 2
        )
    [2] => Array
        (
            [imageID] => 3
        )
    [3] => Array
        (
            [imageID] => 4
        )
) And array 2 Array (
    [0] => Array
        (
            [imageID] => 6
        )
    [1] => Array
        (
            [imageID] => 3
        )
) After intersection instead of me getting 3 as a result, I got the array 1 unchanged. Seems like intersection doesn't take place at all. Anyway to solve this problem? Regards, Leo Reality starts with Dream Quote from php manual, in the reference for the array_intersect function:
*Note: * Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. That's why array_intersect isn't working with your arrays. If you're using PHP5 you could use array_uintersect, and compare the items by the imageID: function compareByImageID($elem1, $elem2) {
       return $elem1['imageID'] - $elem2['imageID'];
} $intersection = array_uinsersect($array1, $array2, 'compareByImageID'); Or you can do the following, which works in PHP4, but is not as versatile as array_uintersect: class InArrayFilter {
       var $arr;
       function InArrayFilter($arr) {
           $this->arr = $arr;
       }
       function filterFunction($elem) {
           return in_array($elem, $this->arr);
       }
} $filter = new InArrayFilter($array2); $intersection = array_filter($array1, array($filter, 'filterFunction'));

« previous php.general (#246219) next »