Search code examples
phpmysqlarraysarray-intersect

How to match array_intersect() values to corresponding key in another array?


Lets say this is my sql database column values:

Result  -      Reference

  1                A1
  2                A2
  3                A3
  4                A4
  5                A5

After fetching the above columns, I have the following arrays:

$inputValue = array(1,3,5);  //This is the User Input

$result = array(1,2,3,4,5); //This is the mysql fetched result of 'Results' column

$reference = array('A1','A2','A3','A4','A5'); //This is the fetched result of 'Reference' column

$filteredData = array_intersect($inputValue, $result);

print_r($filteredData);

When I do array_intersect($inputValue, $result); this gives the output:

Array ( [0] => 1 
    [1] => 3 
    [2] => 5 )

Now after the array_intersect, how will I store the corresponding references into another array? Meaning, after the intersect, the $filteredData has the array values 1,3,5. Now I also want the corresponding references to be stored in a separate array which should have this value: $MatchingReference = array(A1,A3,A5);

How is this done?


Solution

  • Combine the two arrays from the database into an associative array. Then use the user input to select only a subset of keys.

    $filteredData = array_intersect_key(
        array_combine($result, $reference), 
        array_flip($inputValue)
    );