dqkv0603 2012-11-21 20:48
浏览 60
已采纳

php内置于foreach循环当前的迭代中的php

I have an associative array. Two dimensions which I am iterating through like this

foreach ( $order_information as $sector_index => $sector_value ){
echo 'sector : ' . current($order_information) ;
echo '<br>';
    foreach ( $sector_value as $line_index => $line_value ){

    }
}

The current() is an attempt to get the iteration the loop is in. It seems like this should give me that. However, elsewhere on that page there is the suggestions that you just do like

$index = 0
foreach ( $array as $key => $val ) {
    echo $index;
    $index++;
} 

I wonder if I am using current incorrectly, as echo 'sector : ' . current($order_information); just prints sector : Array

Is $index++ bad syntax? Is there a better way to do this?

  • 写回答

1条回答 默认 最新

  • duancan65665 2012-11-21 20:53
    关注

    Answer

    As far as I know there is no build in numeric counter in a foreach loop in PHP.

    So you need your own counter variable. Your example code looks quite good to do that.

    $index = 0;
    foreach($array as $key => $val) {
        $index++;
    }
    

    By the way, $index++; is fine.

    Example

    Here is an example illustrating which variable stores which value.

    $array = array(
        "first"  => 100,
        "secnd" => 200,
        "third"  => 300,
    );
    
    $index = 0;
    foreach($array as $key => $val) {
        echo "index: " . $index . ", ";
        echo "key: "   . $key   . ", ";
        echo "value: " . $val   . "
    ";
        $index++;
    }
    

    The output will be that.

    index: 0, key: first, value: 100
    index: 1, key: secnd, value: 200
    index: 2, key: third, value: 300
    

    Current-Function

    I think you misunderstood current($array). It gives you the value pointed by an internal array pointer, which can be moved using next($array), prev($array) and end($array).

    Take a look at the manual to make thinks clear.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?