如何基于循环内的信息知道何时重复循环

时间:2012-06-02 11:56:19

标签: php

我是php的新手,仍在努力掌握这些概念。
我的问题是,如何根据开始循环后仅提供的信息来更改是否循环?

这是我提出的代码,有评论试图解释我的想法。
如果有一个或多个页面,我基本上都试图让每个页面都“完成”。

注意:$ object包含可能跨页面的结果集。如果它确实跨越页面,那么$ object->分页将存在,否则它将不存在。 $ object-> pagination-> pages =总页数,$ object-> pagination-> pages =当前页面。

//get first page. some how this needs to be a loop i'm guessing.
$page = 1;
$url = "api/products/page/" . $page;
$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER,array ("Content-Type: Content-Type: application/json; charset=utf-8"));
        curl_setopt($ch, CURLOPT_HTTPHEADER,array ("Accept: application/json"));
        curl_setopt($ch, CURLOPT_USERPWD, "username-password");
        $contents = curl_exec ($ch);
        curl_close ($ch);
        $object = json_decode($contents);
//$data returned with product info and pagination info if there is more than one page.


//now check in that first page to see if there is other pages set
if(isset($object->pagination)){
        while($object->pagination->page < $object->pagination->pages) {
        $page = $page+1 ;
        //do some business
    } else {//stop going through the pages}
}

4 个答案:

答案 0 :(得分:1)

<?php 

$object->pagination->page = 1;
$url = "api/products/page/" . $object->pagination->page;

//$url is used for cURL. $object returned with product info and pagination info if there is more than one page.
$object //JSON decoded object returned from cURL. 

//now check in that first page to see if there is other pages set
if(isset($object->pagination)){
    while($object->pagination->page pagination->pages) 
    {

        //do some business

        $object->pagination->page++;
    } 
}
?>

答案 1 :(得分:0)

我认为你的意思是遍历对象中的所有页面:

if (isset($object->pagination)) { 
    while ($object->pagination->page < $object->pagination->pages) { 
        $object->pagination->page++; // $x++ is the same as $x = $x+1
        //do some business 
    } 
} 

答案 2 :(得分:0)

试试这个:

if(is_array($values){
      foreach($values as $value){
         //do some  with you value
      }
}else{
  // do something with $values
}

答案 3 :(得分:-1)

以下是一个例子:

$x = 1;

// Loop 1 through 5
while( $x <= 5 )
{
   // Output x
   echo("$x\n");

   // Check if x is a certain value and do something different
   if($x==3)
   {
      echo("Almost there...\n");
   }

   // Increment x
   $x++;
}

// This outputs...
// 1
// 2
// 3
// Almost there...
// 4
// 5