I have a situation where I have two arrays and I use one array(A) to determine which elements of the second array(B) I need to use. Since I will be combing B multiple times and each time I will not need the previously used elements I have written a function that I call sift_array.
function sift_array(&$array, $key, $value){
foreach($array as $element){
if($element[$key] == $value){$temp[] = $element;}
else{$temp2[] = $element;}
}
$array = $temp2;
return $temp;
}
I am curious if there is a faster way to perform this function.
Here is an example of how I use this function.
In my web app users can set up a ‘bot’ to perform an action so many times while they are away/logged off. I have a program that will run periodically to operate the bots. The bots can not run the same action if it was the last bot to do so.
The bots array has 3 key elements : account_id, action_id, job_id
The job array has 1 key element : job_id.
I pass in the bots array then for the $key I pass ‘job_id’ and for the $value I pass the job id I am working with, say job 1.
$runTheseBots = sift_array($bots, 'job_id', 1);
executeBots($runTheseBots);
This will have a faster execution time because all the bots that deal with job 1 are already handled.
$runTheseBots = sift_array($bots, 'job_id', 2);
executeBots($runTheseBots);
There are plenty of ways to implement this, but I’ll just comment on how you’ve done it:
Here we are saving memory and time (well, maybe not time… benchmark to see) by not making a copy of
$array. Simply delete the element after you move it to the new array.Again, I don’t claim this to be the best way of doing it… just a way to optimize what you’ve already done.