0

Hi all:

I am having a heck of a time here... and can't seem to get this to work. I want to intersect arrays that are subset within a multi-dimensional array.

For example, Take the following array:

Array ( [0] => Array ( [0] => 2014 [1] => 2035 [2]=>1999 [3]=>1942 ) [1] => Array ( [0] => 1894 [1] => 1957 [2] => 1963 [3] => 2035 [4]=>1942) )

The intersection of the arrays within the above array should be this array:
Array([0] => 2035 [1] => 1942)

The keys of the subset arrays are irrelevant.

Problem is, I can't figure out the code to help me do this.

----

I've tried to use this user defined function >>

function array_intersect_m($m_array) {
$intersection = $m_array[0];
for ($i=1; $i < count($m_array); $i++) {
$intersection = array_intersect($m_array[$i], $intersection);
}
return $intersection;
}

And sent the above array example into it, but I am getting no result?!?

Any ideas... help?

Thanks,
Chris in DC

3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by kireol
0

I wrote a similar function (i think it's kind of what yer looking for) for work. Yer welcome to modify it. Just change the return part to build a new array of common elements. There might be a better way to do this, but it works :)

public function value_exists_in_array($haystack,$needles)
{
    foreach($haystack as $pieceOfHay)
    {
        $addToArray = true;
        foreach($needles as $field => $searchValue)
        {
            if($pieceOfHay[$field]==$searchValue)
            {
//You probably want to build a new array here
                return true;
            }
        }
    }

    return false;
}
0

Try It

$a=array (array ( "2014", "2035" ,"1999","1942" ),array ("1894","1957","1963","2035" ,"1942"));

$a_res=array_intersect($a[0],$a[1]);

print_r($a_res);

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.