0

我是 php 新手,仍在尝试掌握这些概念。
我的问题是,如何根据仅在启动循环后可用的信息来更改是否循环?

这是我想出的代码,带有注释以尝试解释我的想法。
我基本上是在尝试为每个页面完成“业务”,如果有 1 个或多个。

注意:$object 包含可能跨越页面的结果集。如果它确实跨越页面,那么 $object->pagination 将存在,否则它将不存在。$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

4 回答 4

1
<?php

$对象->分页->页面= 1;
$url = "api/products/page/" 。$对象->分页->页面;

//$url 用于 cURL。$object 如果有超过一页,则返回产品信息和分页信息。
$object //从 cURL 返回的 JSON 解码对象。

//现在检查第一页以查看是否设置了其他页面
if(isset($object->pagination)){
    while($object->pagination->page 分页->pages)
    {

        //做一些生意

        $对象->分页->页面++;
    }
}
?>
于 2012-06-02T12:11:11.513 回答
0

尝试这个:

if(is_array($values){
      foreach($values as $value){
         //do some  with you value
      }
}else{
  // do something with $values
}
于 2012-06-02T14:38:06.383 回答
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 
    } 
} 
于 2012-06-02T12:07:25.310 回答
-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
于 2012-06-02T12:00:30.013 回答