PHP For循环跳过第一个结果

时间:2017-09-25 07:36:52

标签: php

我正在尝试使用for循环填充数组。这样做是为了获得某本书的页数。但是在执行代码时,它会跳过数组中的第一个对象。谁能告诉我为什么? (我认为这是因为$ i从1开始而不是0但这似乎没有改变任何东西)

if(!empty($article['finishing'])){
    $numPages = $article['copies'];
    $arrayIndexNumber = [];

    for($i=1; $i <= $numPages; $i++){
        $arrayIndexNumber[] = $i;
    }

    if(count($arrayIndexNumber) >= 1 ){

        if(count($arrayIndexNumber) == 1){
            $output['attributes']['EFPageRange'] = 1;
            $print_jobs[$article['id']][] = $output;
        }

        if(count($arrayIndexNumber) > 1){
            $comma_separated1 = implode(", ", ['1', $article['copies']]);
            $output['attributes']['EFPageRange'] = $comma_separated1;
            $print_jobs[$article['id']][] = $output;
        }

        array_shift($arrayIndexNumber);
        array_pop($arrayIndexNumber);
        $comma_separated2 = implode(", ", $arrayIndexNumber);
        $output['attributes']['EFPageRange'] = $comma_separated2;

        if(count($arrayIndexNumber) >= 2){
            $print_jobs[$article['id']][] = $output;
        }
    }
    $article['file_url'] =  'i has finishing';
    $output['attributes']['username'] = $article['file_url'];
}

以上代码输出:

[0] => Array
   (
      [attributes] => Array
          (
              [title] => 277569
              [EFPrintSize] => a4
              [num copies] => 1
              [num pages] => 119
              [EFPCName] => 80
              [EFDuplex] => TopTop
              [EFPageRange] => 1, 119
          )

  )

而不是:

[0] => Array
  (
      [attributes] => Array
          (
              [title] => 277564
              [EFPrintSize] => a4
              [num copies] => 1
              [num pages] => 45
              [EFPCName] => 80
              [EFDuplex] => false
              [EFPageRange] => 1, 45
              [username] => i has finishing
              [EFColorMode] => Grayscale
          )

  )

2 个答案:

答案 0 :(得分:1)

由于array_shift:

,您的第一个数组元素被删除
array_shift($arrayIndexNumber);
  

array_shift

     

array_shift - 关闭一个元素   数组的开头

调试代码:

for($i=1; $i <= $numPages; $i++){
    $arrayIndexNumber[] = $i;
}
echo '<pre>';
print_r($arrayIndexNumber); // Check what the array returns

答案 1 :(得分:-1)

php数组索引从零开始计算

for($i=1; $i <= $numPages; $i++)
      ^^^

将其更改为$i=0