douyu7618 2018-08-29 14:16
浏览 60
已采纳

如何只迭代数组的前3个元素并访问键/值?

I was trying to assign each seller their monthly points, based on the amount of products they sell. The numbers, however, are just an example. This is my code so far:

$sellers = array(
    'Edvin'   => 10, 
    'Julio'   =>  9, 
    'Rene'    =>  8, 
    'Jorge'   =>  7, 
    'Marvin'  =>  6,
    'Brayan'  =>  5, 
    'Sergio'  =>  4,   
    'Delfido' =>  3, 
    'Jhon'    =>  2
);

$a = 1;
foreach ($sellers as $seller => $points) {
    while ($a < 4) {
        echo "The seller top " . $a . " is " . $sellers[$a - 1] . ' with ' . $points[$a] . '<br>';
        $a++;
    }
}

I am trying to output this:

The seller top 1 is Edvin with 10<br>
The seller top 2 is Julio with 9<br>
The seller top 3 is Rene with 8<br>
  • 写回答

2条回答 默认 最新

  • dsfdsf23423 2018-08-29 14:24
    关注

    You only want to access the first three elements, so slice the array before looping, you can increment the counter as you iterate.

    Code: (Demo)

    $sellers = array('Edvin' => 10, 'Julio' => 9, 'Rene' => 8, 'Jorge' =>7, 'Marvin' => 6,
                        'Brayan' => 5, 'Sergio' => 4, 'Delfido' => 3, 'Jhon' => 2);
    
    $i = 0;
    foreach (array_slice($sellers, 0, 3) as $seller => $points) {
        echo "The seller top " . ++$i . " is $seller with $points<br>";
    }
    

    Output:

    The seller top 1 is Edvin with 10<br>
    The seller top 2 is Julio with 9<br>
    The seller top 3 is Rene with 8<br>
    

    If you want to control the loop with the counter and omit the array_slice() call, you will need to write a loop break.

    $i = 0;
    foreach ($sellers as $seller => $points) {
        echo "The seller top " . ++$i . " is $seller with $points<br>";
        if ($i == 3) break;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误