您好我正在尝试从数组中打印出有序列表。 这是我现在的代码:
<?php
$Salespeople = array(
"Hiroshi Morinaga"=>57,
"Judith Stein"=>44,
"Jose Martinez"=>26,
"Tyrone Winters"=>22,
"Raja Singh"=>21);
foreach ($Salespeople as $Salesperson) {
echo key($Salespeople) . ": $Salesperson cars<br />";
next($Salespeople);
}
?>
我遇到的问题是结果如下:
Judith Stein: 57 cars
Jose Martinez: 44 cars
Tyrone Winters: 26 cars
Raja Singh: 22 cars
: 21 cars
如何制作它以显示所有名称,而不是像这样打印出来?
Hiroshi Morinaga: 57
Judith Stein: 44 cars
Jose Martinez: 26 cars
Tyrone Winter: 22 cars
Raja Singh: 21 cars
谢谢。
答案 0 :(得分:3)
想要这样的东西吗?
foreach($Salespeople as $fullname => $cars)
{
echo $fullname . ": " . $cars . " cars<br />";
}
答案 1 :(得分:1)
使用foreach更简单:
foreach ($Salespeople as $Salesperson => $Cars) {
echo $Salesperson . ": $Cars cars<br />";
}
答案 2 :(得分:1)
foreach
将遍历列表本身 - 您无需使用key
或next
。
foreach ($Salespeople as $name => $number) {
echo $name . ": $number cars<br />";
}
答案 3 :(得分:0)
只是为了好玩,您还可以使用array_map
:
function echoSalesperson($v) {
echo $v . ": $Salesperson cars<br />"
}
array_map($Salespeople,'echoSalesperson');