2017-04-11 77 views
0

我正在处理一个请求来自在线服务的发票的脚本 - 一次返回100个发票。我已经获得了基本要求,可以返回前100个发票并循环显示结果。这里是我当前的代码:PHP循环实现

// set pagination to page 1 
$page = 1; 

// Request Invoices 
$response = $XeroOAuth->request('GET', $XeroOAuth->url('Invoices', 'core'), array('page' => $page)); 


    if ($XeroOAuth->response['code'] == 200) { 

     // Parse Invoices 
     $invoices = $XeroOAuth->parseResponse($XeroOAuth->response['response'], $XeroOAuth->response['format']); 

     // Get total found invoices 
     $totalInvoices = count($invoices->Invoices[0]); 


     // Loop through found invoices 
     if ($totalInvoices > 0) { 

      foreach ($invoices->Invoices->Invoice as $invoice) { 
       $invoiceNumber = $invoice->InvoiceNumber; 
       // Process Invoice as required 
      } 

     } 

    } else { 

     // Request Error 
    } 

我需要扩展这个如下:

  • 如果返回了100张的发票我需要1递增$页面,然后执行另一个请求来获得的第2页发票和处理这些
  • 继续,直到发票总数返回的最后一个请求小于100则退出后

我不能得到的逻辑纠正在这里跟另一个循环扩展,这样下去的请求,直到它得到小于100张的发票

回答

1

这应该工作:

<?php 

$breakFlag = 0; 

// set pagination to page 1 
$page = 1; 

do { 

    // Request Invoices 
    $response = $XeroOAuth->request('GET', $XeroOAuth->url('Invoices', 'core'), array('page' => $page)); 

    if ($XeroOAuth->response['code'] == 200) { 

     // Parse Invoices 
     $invoices = $XeroOAuth->parseResponse($XeroOAuth->response['response'], $XeroOAuth->response['format']); 

     // Get total found invoices 
     $totalInvoices = count($invoices->Invoices[0]); 

     if ($totalInvoices < 100) { 
      $breakFlag = 1; 
     } 

     // Loop through found invoices 
     if ($totalInvoices > 0) { 

      foreach ($invoices->Invoices->Invoice as $invoice) { 
       $invoiceNumber = $invoice->InvoiceNumber; 
       // Process Invoice as required 
      } 

     } 

     $page += 1; 

    } else { 

     // Request Error 
    } 
} while($breakFlag == 0) 
1

个人而言,我包你的代码中的函数,然后调用它只要你需要,就可以从内部获得。

fetchInvoices(1); 

function fetchInvoices($page) { 
    // Request Invoices 
    $response = $XeroOAuth->request('GET', $XeroOAuth->url('Invoices', 'core'), array('page' => $page)); 

    if ($XeroOAuth->response['code'] == 200) { 

     // Parse Invoices 
     $invoices = $XeroOAuth->parseResponse($XeroOAuth->response['response'], $XeroOAuth->response['format']); 

     // Get total found invoices 
    $totalInvoices = count($invoices->Invoices[0]); 


     // Loop through found invoices 
     if ($totalInvoices > 0) { 

      foreach ($invoices->Invoices->Invoice as $invoice) { 
       $invoiceNumber = $invoice->InvoiceNumber; 
       // Process Invoice as required 
      } 
     } 

     if($totalInvoices == 100) { 
      fetchInvoices($page + 1) 
     } 
    } else { 

     // Request Error 
    } 
}