PHP Foreach loop too slow when applied on large arrays

时间:2018-06-04 17:26:15

标签: php arrays performance foreach

So, basically, i have to loop thought an array of 25000 items, then compare each item with another array's ID and if the ID's from the first array and the second match then create another array of the matched items. That looks something like this.

foreach ($all_games as $game) {
  foreach ($user_games_ids as $user_game_id) {
     if ($user_game_id == $game["appid"]) {
         $game_details['title'][] = $game["title"];
         $game_details['price'][] = $game["price"];
         $game_details['image'][] = $game["image_url"];
         $game_details['appid'][] = $game["appid"];
     }
  }
}

I tested this loop with only 2500 records from the first array ($all_games) and about 2000 records from the second array ($user_games_ids) and as far as i figured, it takes about 10 seconds for the execution of that chunk of code, only the loops execution. Is that normal? Should that take that long or I'm I approaching the issue from the wrong side? Is there a way to reduce that time? Because when i apply that code to 25000 records that time will significantly increase.

Any help is appreciated, Thanks.

EDIT: So there is no confusion, I can't use the DB query to improve the performance, although, i have added all 25000 games to the database, i can't do the same for the user games ids. There is no way that i know to get all of the users through that API i'm accessing, and even there is, that would be really a lot of users. I get user games ids on the fly when a user enters it's ID in the form and based on that i use file_get_contents to obtain those ids and then cross reference them with the database that stores all games. Again, that might not be the best way, but only one i could think of at this point.

1 个答案:

答案 0 :(得分:2)

If you re-index the $game array by appid using array_column(), then you can reduce it to one loop and just check if the data isset...

$game = array_column($game,null,"appid");
foreach ($user_games_ids as $user_game_id) {
    if (isset( $game[$user_game_id])) {
        $game_details['title'][] = $game[$user_game_id]["title"];
        $game_details['price'][] = $game[$user_game_id]["price"];
        $game_details['image'][] = $game[$user_game_id]["image_url"];
        $game_details['appid'][] = $game[$user_game_id]["appid"];
    }
}