php - 如何仅迭代数组的前 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>
解决方案
您只想访问前三个元素,因此在循环之前对数组进行切片,您可以在迭代时递增计数器。
代码:(演示)
$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;
}
推荐阅读
- amazon-s3 - amazon athena 和融合模式注册表
- qt - Qml 中的材质样式不加载颜色
- swift - 快速按下按钮时如何更改url
- php - 在 laravel 中显示部分文本
- javascript - 在网站上显示 pdf 文件
- javascript - 输入“process”关键字时,带有 JavaScript 文件的 VS Code 中的 IntelliSense 问题
- angular - 如何在ng2智能表中过滤从valuePreparefunction返回的自定义数据
- javascript - vue v-for 对象道具
- c++ - C++没有匹配的函数来调用
- c# - ASP.NET Core 2.1 - 内存缓存 - 控制器无法访问中间件中设置的值