dongtuojuan8998 2011-04-23 08:01
浏览 13
已采纳

PHP - 没有得到我期望的数组元素

I am paging through the elements of an array. I get the total number of elements in the array with:

$total = count($myarray);

My paging function loads the current element on the page and provides "Previous" and "Next" links that have urls like:

http://myapp.com?page=34

If you click the link I grab that and load it onto the page by getting (I sanitize the $_GET, this is just for example):

$element = $myarray[$_GET['page']];

This should grab the element of the array with a key == $_GET['page'] and it does. However, the problem is that my total count of elements doesn't match some keys because while there are 100 elements in the array, certain numbers are missing so the 100th item actually has a key of 102.

How should I be doing this? Do I need to rewrite the keys to match the available number of elements? Some other method? Thanks for your input.

  • 写回答

3条回答 默认 最新

  • douweng3383 2011-04-23 08:07
    关注

    If you have gaps in the indices, you should reindex the array. You can do that before you generate the links, or probably easier on the receiving page:

    $myarray = array_values($myarray);
    $element = $myarray[$_GET['page']];
    

    This would give you the 100th element, even if it previously had the key 102. (You could use a temporary array of course, if you need to retain the original indexing.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集