如何在API中处理大量数据

时间:2020-04-28 16:51:47

标签: php mysql api

我正在开发一个仪表板API,以通过使用PHP CURL从外部源检索数据并将其显示在前端来进行一些与用户相关的操作(创建用户,更新,转账...)。 一切都运转良好,直到数据库中的数据开始增长为止。

我的看法是,每个管理员登录到仪表板后仅应对其相关用户执行操作,这就是为什么花太多时间从源中检索所有用户,然后检查相关用户的状况并显示给他们的原因。这位管理员。

对于这种操作是否有更好的解决方案?

我尝试使用以下代码从源中检索数据并遍历请求,因为每个请求的数据限制为100。

function get_users($session_id){

    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => "THE_URL",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS =>"{\"offset\": 0,\"limit\": 100}",
      CURLOPT_HTTPHEADER => array(
        "x-api-token: TOKEN",
        "Content-Type: application/json",
      ),
    ));

    $response = curl_exec($curl);
    $data = json_decode($response, true);
    curl_close($curl);

    $allcollection = [];

    foreach ($data['users']  as $key => $value) { 
     if(isset($value['admin']['id'])){
       if($value['admin']['id'] == $session_id){


        array_push($allcollection,$value);

      }
    }}

    $totalrows = $data['nrOfResults'];
    $offset = 100;

    while($totalrows >= 100){
        $newcurl = curl_init();
        curl_setopt_array($newcurl, array(
        CURLOPT_URL => "THE_URL",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS =>"{\"offset\": ".$offset.",\"limit\": 100}",
        CURLOPT_HTTPHEADER => array(
            "x-api-token: token",
            "Content-Type: application/json",
      ),
    ));

        $newresponse = curl_exec($newcurl);
        $newdata = json_decode($newresponse, true);
        curl_close($newcurl);

        foreach ($newdata['users']  as $key => $value) { 
            if(isset($value['admin']['id'])){
              if($value['admin']['id'] == $session_id){


                array_push($allcollection,$value);

             }
           }}



        $totalrows = $totalrows - 100; 
        $offset = $offset + 100;
    }



    return $allcollection; }

0 个答案:

没有答案
相关问题