【问题标题】:codeigniter - get current array position while doing foreach $object->result_array()codeigniter - 在执行 foreach $object->result_array() 时获取当前数组位置
【发布时间】:2010-08-04 16:18:35
【问题描述】:

在执行foreach $object->result_array()时获取当前数组位置指针

嗨, 考虑一下这个,一个案例。

foreach($object->result_array() as $rs)
{
    //how do i display the current array element index that is the iteration index.
    //i want to call a function when the iterator is in the last-1 position.
    // and more specifically i want to use it in this place and not any other for(;;) loops.
    // and even it is an example with other loops then that is fine.
}

应该有一个选项或使用 current() 函数。 我已经尝试过,但我仍然需要做一些分析...... 我发布了这个帖子,而不是调试和跟踪数组元素。

最重要的是,是否可以使用 for 循环来做到这一点?

【问题讨论】:

    标签: codeigniter


    【解决方案1】:

    像这样添加=> $key也可以获取密钥:

    foreach($object->result_array() as $rs => $key)
    {
       echo $key;
    }
    

    最重要的是有可能做到吗 有for循环吗?

    是这样的:

    for($i = 0; $i < count($object->result_array()); $i++)
    {
      // your code...
    }
    

    【讨论】:

    • 工作。谢谢你。但是...您所说的是对的,但是您似乎只想给我一些想法,而不是提供更多代码。不管怎样,我得到了我想要的,我投票给你。谢谢你。在该代码中,我想要 $rs 这是当前索引号,即数组位置或迭代器。在 for 循环中,我们需要执行 $object->result_array[$i]['f​​ield']无论如何,我尝试过自己,通过这种方式让我们的分析更加清晰。我从你的代码中假设并编造了这个。
    • @Jayapal Chandran:这是个好消息,我尽可能地回答了你的问题。很高兴看到你自己解决了剩下的部分,这对程序员来说总是一件好事:)
    • 是的。这是我的代码。 $list = $object->result_array(); $length = sizeof($list); foreach($list as $key=>$value) { if ($key==$length-1) echo '这是最后一项'; if ($key==$length-2) echo 'This is the item before the last item'; }
    • 我想知道您是如何立即发帖的。你有任何 api 吗?如果有,请给我一个参考,我也会在我身边实施它,以便我可以监控新的问题和我的问题的答案。
    • 为什么在 cmets 部分我们不能发布代码?我们是否必须像在其他论坛(vbulletin)中一样回答我们自己的问题?
    猜你喜欢
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 2011-06-13
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多