Bhoomi Shah
Bhoomi Shah

Reputation: 71

How to Search Second Array Data in First Array Data?

In php, i am new in php anybody help me for this? i have two arrays , in Array2 i have two records, i want to check Data of Array2 whether in Array1 or not , how can i check the data of Array2 in Array1 its available or not !

Thanks in advance

Array1

    [items] => Array
    (
        [0] => Array
            (
                [abc] => z1
                [xyz] => cool
                [val] => 2.32
                [color] => D
             )
         [1] // i have 5o records in array1
     );

Array 2

    [items] => SearchArray
    (
        [0] => Array
            (
                [abc] => z1
                [xyz] => cool
                [val] => 2.32
                [color] => D
             )
         [1] // i have 2 records
     );

Upvotes: 1

Views: 48

Answers (2)

user2941651
user2941651

Reputation:

Please try this code - I hope it helpes some way :

$matches = array();

for($i2 = 0; $i2 < count($Array2); $i2++)
{
    for($i1 = 0; $i1 < count($Array1); $i1++)
    {
        $bMatch = TRUE;
        foreach($Array1[$i1] as $key => $val)
        {
            if($Array2[$i2][$key] !== $val)
            {
                $bMatch = FALSE;
                break;
            }
        }
        if($bMatch)
        {
            $matches[] = array($i2, $i1);
        }
    }
}

It iterates through both arrays, comparing elements (which in fact are sub arrays) in such way that they are equal only if all elements of sub array from $Array2 are equal to all elements of sub array from $Array1. If the match is found, the pair ($i2, $i1) is added to the $matches array, so in the end, basing on your example, you would have something like:

$matches => array  (
               [0] => array (0, 0)
               ...
            )

I hope the assumption made is the proper one.

Upvotes: 2

Mehmet
Mehmet

Reputation: 3347

Can use array_search method. For more information, check out the manual reference: http://php.net/manual/en/function.array-search.php

Upvotes: 0

Related Questions