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条)

报告相同问题?

悬赏问题

  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。