cem ekkazan
cem ekkazan

Reputation: 15

My for loop is taking too much time

These days, there is an election in Turkey and i am coding a php script to follow elections with an API and I have a for loop in my project to show general results of of all Turkey. This loop is summing up 81 different provinces results but it is taking too much time and sometimes it is not working because it takes more than 30 seconds and my page is not loading. What can I do to reduce this time?

$mi_total_vote = 0;

for ($id=1; $id < 82; $id++) {
  $turkey_data = file_get_contents('http://secim-api.adilsecim.net/2/city/'.$id.'.json');
  $turkey_json = json_decode($turkey_data);
  $mi = $turkey_json->results->mi;
  $mi_total_vote = $mi_total_vote + $mi;
}

JSON files are my API data. I have to sum up them to obtain the results for all Turkey.

Upvotes: 1

Views: 429

Answers (2)

SirPilan
SirPilan

Reputation: 4847

Make a feature out of it :D - Load it asynchronously via ajax

(wont work here cause SOP - but you get the concept ;) )

If you are brave you can perform a loop of all 84 and load them at once - but this will get you unwanted attention pretty fast :P

var i = 1;
var max = 82;
var sum = 0;

function load( i ) {
  $('#status').text( "Loading " + i + " of " + max );
  $.ajax({
    url: 'http://secim-api.adilsecim.net/2/city/' + i + '.json',
    type: 'JSON',
    success: function(msg) {
      sum += msg.results.mi;
      
      if( i < 82 ) {
        load(i++);
      } else {
        $('#status').text( "Loading " + i + " of " + max + " DONE" );
      }
    }
  });
}

load(i);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<small><span id="status"></span><br/></small>
<br/>
Result: <span id="result">0</span>

Upvotes: 1

Supun Praneeth
Supun Praneeth

Reputation: 3160

Use cURL, it's faster:

<?php
    $mi_total_vote = 0;

    for ($id=1; $id < 82; $id++) {

       $ch =  curl_init('http://secim-api.adilsecim.net/2/city/1.json');
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
       $turkey_data = curl_exec($ch);  

       $turkey_json = json_decode($turkey_data);
       $mi = $turkey_json->results->mi;
       $mi_total_vote = $mi_total_vote + $mi;
    }


?>

Upvotes: 2

Related Questions