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)
);
Question
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 2
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)
);
OTHER TIPS
I would try this:
$filteredReferences = array();
foreach($filteredData as $key) {
$filteredReferences[] = $reference[$key-1];
}
If this was a task in my own application, I would definitely implement the data filter with SQL instead of PHP.
Otherwise, you going to need perform a few manipulations to enjoy efficient key-based filtration and reach your desired output. (Demo)
var_export(
array_intersect_key(
array_column($resultSet, 'reference', 'result'),
array_flip($inputValue)
)
);