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

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.