【问题标题】:How to get this value by using For loop in array php如何通过在数组 php 中使用 For 循环来获取此值
【发布时间】:2018-04-18 10:47:11
【问题描述】:
<?php
    $citySurvey = array("London", "Paris", "Rome", "Rome", "Paris",
    "Paris", "Paris", "London", "Rome", "Rome",
    "Paris", "London", "Paris", "London", "London",
    "London", "Paris", "London", "Paris", "Rome");

    print ("<h1>CITY SURVEY RESULTS</h1>");
    print ("<table border = \"1\">");
    print ("<tr><td>cities</td><td>Counts</td></tr>");


    print ("</table>");

?>

我需要使用 For 循环来让这个数组代码工作。 我需要知道选择这些城市的人数。

我需要在表格中显示结果。第一列是城市名称,第二列是计数。

感谢您的帮助。

【问题讨论】:

标签: php arrays loops for-loop


【解决方案1】:

1.始终尽量将 HTML 与 PHP 分开。

2.您需要使用array_count_values()foreach() 来获得所需的输出

代码需要如下:-

<?php
    $citySurvey = array("London", "Paris", "Rome", "Rome", "Paris",
    "Paris", "Paris", "London", "Rome", "Rome",
    "Paris", "London", "Paris", "London", "London",
    "London", "Paris", "London", "Paris", "Rome");

    $count_city_array = array_count_values($citySurvey);
?>
<h1>CITY SURVEY RESULTS</h1>
<table border="1">
    <tr>
        <td>cities</td>
        <td>Counts</td>
    </tr>
<?php

foreach($count_city_array as $key=>$val){?>
    <tr>
        <td><?php echo $key;?></td>
        <td><?php echo $val;?></td>
    </tr>

 <?php } ?>
</table>

在我的本地屏幕上输出:- https://prnt.sc/j6u4ay

【讨论】:

  • 代码有效!谢谢,我需要对此代码进行一些解释。为什么我不能使用 For 循环来找出值?
  • @BoramLamppa foreach() 专门为数组迭代而设计,它总是自己处理索引,这就是为什么总是比for() 循环更可取。您也可以使用for() 循环。
  • @BoramLamppa 很高兴为您提供帮助:):)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-16
  • 2014-06-11
  • 2016-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多