在php中一次取10个数组元素?

时间:2014-05-19 16:29:31

标签: php arrays

       echo "<table title='mxit:table:full' style='width: 100%' width='100%'><colgroup span='2' width='50%'></colgroup>";




        foreach($arr['chart_data'] as $key => $element){



          echo "<tr>";


            foreach($element as $subkey => $subelement){

              // $subelement =chop($subelement,'DIRECTSegment');

                 if($subkey++ < 2) {
                if($key == 0)
                {

               echo "<td align='center;' style='color:white;'>$subelement</td>";
                }

                else if($subkey == 1)
                {
                    echo "<td align='center;' style='color:white;'>$subelement</td>";   
                }

                else
                {

                echo "<td align='center;' style='color:white;'><a href='getdata.php?key=$key'>".$subelement."</a></td>";
                }
                 }

            }

              }
           echo "</tr>";

       echo "</table>";

我如何一次只获取数组$ arr [&#39; chart_data&#39;]中的10个元素?

2 个答案:

答案 0 :(得分:2)

设置一个计数器,然后在break命中10时循环$count

$count = 0;
/* loop here */
if ($count == 10) break;

答案 1 :(得分:0)

无论如何,对于那些给我负面投票并为了我自己的改善的人,我解决了我的问题:

这就是我所做的:

 $totalfiles = count($arr['chart_data']);
  $limit = 10;
  $pages = ceil($totalfiles / $limit);


  if (!isset($_GET['startrow']) or!is_numeric($_GET['startrow'])) {
      //we give the value of the starting row to 0 because nothing was found in URL
      $startrow = 0;
      //otherwise we take the value from the URL
  } else {
      $startrow = (int) $_GET['startrow'];
  }

  echo "<table title='mxit:table:full' style='width: 100%' width='100%'><colgroup span='2' width='50%'></colgroup>";


  $data = array_slice($arr['chart_data'], $startrow, 10); // same as offset 0 limit 50 in sql

  foreach($data as $key => $element) {



      echo "<tr>";


      foreach($element as $subkey => $subelement) {

          $subelement = chop($subelement, 'DIRECTSegment');

          if ($subkey++ < 2) {
              if ($key == 0 && $startrow == 0) {

                  echo "<td align='center;' style='color:white;'>$subelement</td>";
              } else if ($subkey == 1) {
                  echo "<td align='center;' style='color:white;'>$subelement</td>";
              } else {

                  echo "<td align='center;' style='color:white;'><a href='getdata.php?key=$key'>".$subelement.
                  "</a></td>";
              }
          }

      }
      echo "</tr>";

  }


  echo "</table>";




  /* free result set */
  $result - > close();
  }


  /* close connection */
  $mysqli - > close();

   //now this is the link..
  echo '<a href="'.$_SERVER['PHP_SELF'].
  '?startrow='.($startrow + 10).
  '">Next</a>';

  $prev = $startrow - 10;

   //only print a "Previous" link if a "Next" was clicked
  if ($prev >= 0)

      echo '  <a href="'.$_SERVER['PHP_SELF'].
  '?startrow='.$prev.
  '">Previous</a>';

实施分页并使用数组切片一次显示10个元素。

感谢所有帮助