How do I filter rows of an array so that only records with a particular value are displayed?
Imagine I am running 2 queries each one against a different database.
The query result from source #1 will be stored in an array. The query result from source #2 will also be stored in an array.
Source #2 records will contain a foreign key that may or may not match up with particular records in an ID field in source #1.
So if I were to loop through source #1 and then I wanted to display only the source #2 records that matched the ID of source #1 is there a handy command within PHP that will allow me to get the filtered results that I could run once each time I ran the loop.
What I woul开发者_JAVA技巧d like to avoid is having a loop within a loop to check the result before determining if it should be displayed (hopefully a built in filter command if available will have less overhead).
Any suggestions on commands that filter an array within PHP?
A row in a given array is either an object or an array. We cannot run array_intersect on the entire result array because array elements are not scalar values.
I would create one loop to store the primary key indices, then call array_filter on it in which the function would check for a valid correspondence.
global $aIds;
$aIds = array();
foreach($array_masters as $item) {
$aIds[] = $item->master_id;
}
function filter_correspondant($row) {
global $aIds;
return in_array($row->slave_id, $aIds);
}
$array_slaves_filtered = array_filter($array_slaves, 'filter_correspondant');
In the above snippet, the two arrays are $array_masters and $array_slaves. The resulting intersected array is $array_slaves_filtered which contains rows from $array_slaves that match the foreign key constraint.
Sounds like a job for array_intersect.
That depends on what you're optimizing for.
- Lines of code: use array_intersect as mentioned by Matt V (possibly after some preprocessing).
- Memory / performance: create a dictionary (associative array) where the keys are the IDs of source #1. If memory is a concern, discard the rows once they are processed. Values can be anything, say TRUE. You can now filter the array from source #2 using
isset($dict[$id])
, which runs in near constant time.array_filter
can be useful here.
精彩评论