1

I am creating a search function in which in need to find matching results from two arrays $array1 is set of keywords for which i am performing search in $array2 which is multidimensional array

Example of Arrays:

$array1 = ['Agriculture & Farming','Modern','Monograms'];
$array2 = [[1,"Agriculture & Farming","Bold","000"],[2,"Agriculture & Farming","Bold","f44336"],[3,"Agriculture & Farming","Bold","E91E63"],[4,"Agriculture & Farming","Bold","9C27B0"],[5,"Agriculture & Farming","Bold","673AB7"],[6,"Agriculture & Farming","Bold","3F51B5"],[7,"Agriculture & Farming","Bold","2196F3"];

I need to find matching keywords item id from $arrays2 but its not working i looped through both arrays and match but wrong results showing

This is how i am trying now but its giving wrong results:

foreach($array2 as $itemkey) {

    $k1 = $itemkey[1];
    $k2 = $itemkey[2];
    $k3 = $itemkey[3];
    $ResutItem= $item;

    foreach($array1 as $searckKey ) {

        if ($searckKey == $k1 || $searckKey == $k2 || $searckKey == $k3) {

            echo implode(" ", $ResutItem).
            '<br>';

        }

    }

}
  • 1
    Possible duplicate of [Checking to see if one array's elements are in another array in PHP](https://stackoverflow.com/questions/523796/checking-to-see-if-one-arrays-elements-are-in-another-array-in-php) – William Perron May 28 '18 at 20:10

1 Answers1

0

You can use array_intersect.
This will give you an array where key is in what subarray of array2 the match is.
And the values are the matching values.

Foreach($array2 as $key => $arr){
    $match[$key] = array_merge([$array2[$key][0]], array_intersect($arr, $array1));
}

Var_dump($match);

https://3v4l.org/vVCiQ

Andreas
  • 23,610
  • 6
  • 30
  • 62
  • hey one more thing how can i store matching items key from array2 – Sunil meena May 28 '18 at 19:35
  • I don't understand, that is what you get in $match. Or what are you looking for? Can you give an example output? Edit your question with what you expect – Andreas May 28 '18 at 19:49
  • Updated array example in question what i need is ID of matching item from array2 like in example array arrays like this [1,"Agriculture & Farming","Bold","000"]... here ID is **1** – Sunil meena May 28 '18 at 20:05
  • See update, now I use array_merge to add item 0 of the array with the matching parts. – Andreas May 28 '18 at 20:15
  • i am getting id now by using this !empty(array_intersect($people, $criminals)) ..thanks again have a nice day ! – Sunil meena May 28 '18 at 20:22