首页 > 解决方案 > 如何仅迭代数组的前 3 个元素并访问键/值?

问题描述

我试图根据他们销售的产品数量为每个卖家分配他们的每月积分。然而,这些数字只是一个例子。到目前为止,这是我的代码:

$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++;
    }
}

我正在尝试输出这个:

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>

标签: phparraysloopsslice

解决方案


您只想访问前三个元素,因此在循环之前对数组进行切片,您可以在迭代时递增计数器。

代码:(演示

$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>";
}

输出:

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>

如果要使用计数器控制循环并省略array_slice()调用,则需要编写循环中断。

$i = 0;
foreach ($sellers as $seller => $points) {
    echo "The seller top " . ++$i . " is $seller with $points<br>";
    if ($i == 3) break;
}

推荐阅读