【问题标题】:My for loop is taking too much time我的 for 循环花费了太多时间
【发布时间】:2018-06-23 19:37:14
【问题描述】:

这些天,土耳其有一场选举,我正在编写一个 php 脚本来使用 API 来跟踪选举,我的项目中有一个 for 循环来显示所有土耳其的一般结果。这个循环总结了 81 个不同省份的结果,但它花费了太多时间,有时它不起作用,因为它需要 30 多秒并且我的页面没有加载。我可以做些什么来减少这个时间?

$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 文件是我的 API 数据。我必须对它们进行总结以获得所有土耳其的结果。

【问题讨论】:

  • 您几乎无法减少发出 HTTP 请求所需的时间...您是否无法在单个文件中获得这些结果?
  • 遗憾的是,没有办法将它们放在一个文件中:(

标签: php json loops for-loop


【解决方案1】:

使用 cURL,速度更快:

<?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;
    }


?>

【讨论】:

  • 这没什么大不了的:/
  • @cemekkazan 对我来说只花了几秒钟。在phpfiddle.org中尝试您的代码
  • @SupunPraneeth 你说得对,花了我 1.5 秒 - 但也许他的服务器连接有限
  • 我认为我的服务器中的 cURL 有问题
  • 是的,但我解决了它,但仍然没有太大区别,file_get_contents 需要 12 秒,curl 需要 9 秒
【解决方案2】:

从中创建一个特性 :D - 通过 ajax 异步加载它

(不会在这里工作,因为SOP - 但你明白了这个概念;))

如果你够勇敢,你可以执行所有 84 个循环并立即加载它们 - 但这会很快引起你不必要的注意: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>

【讨论】:

  • 这是个好主意,但仍然需要太多时间,人们不想等待
猜你喜欢
  • 1970-01-01
  • 2016-12-08
  • 2018-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 2017-02-15
  • 2020-07-23
相关资源
最近更新 更多