简体   繁体   English

PHP 来自数组的有序列表

[英]PHP ordered list from an array

Hi I'm trying to make an ordered list print out from an array.嗨,我正在尝试从数组中打印出有序列表。 This is my code as of now:这是我现在的代码:

    <?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);
    }
    ?>

the problem i have is that the outcome is this:我的问题是结果是这样的:

    Judith Stein: 57 cars
    Jose Martinez: 44 cars
    Tyrone Winters: 26 cars
    Raja Singh: 22 cars
    : 21 cars

How can i make it so it shows all the names and instead print out like this?我怎样才能使它显示所有名称,而不是像这样打印出来?

    Hiroshi Morinaga: 57
    Judith Stein: 44 cars
    Jose Martinez: 26 cars
    Tyrone Winter: 22 cars
    Raja Singh: 21 cars

Thank you.谢谢你。

do want something like this?想要这样的东西吗?

foreach($Salespeople as $fullname => $cars) 
{
    echo $fullname . ": " . $cars . " cars<br />";
}

Use foreach just simplier:使用 foreach 更简单:

foreach ($Salespeople as $Salesperson => $Cars) {
    echo $Salesperson . ": $Cars cars<br />";
}

foreach will iterate over the list itself - you don't need to use key or next . foreach将遍历列表本身 - 您不需要使用keynext

foreach ($Salespeople as $name => $number) {
    echo $name . ": $number cars<br />";
}

Just for fun, you could also use array_map :只是为了好玩,您还可以使用array_map

 function echoSalesperson($v) { 
  echo $v . ": $Salesperson cars<br />" 
 }

 array_map($Salespeople,'echoSalesperson');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM