以升序显示下一行上相同数组的值

时间:2017-03-22 12:07:34

标签: php arrays sorting

我正在练习PHP,而且我似乎无法按升序排列。

<?php
$cities=array (
  "Tokyo",
  "Mexico City",
  "New York City",
  "Mumbai",
  "Seoul",
  "Shanghai",
  "Lagos",
  "Buenos Aires",
  "Cairo",
  "London" 
  );

foreach($cities as $c){
  echo "$c, ";
}

sort ($cities);

foreach($cities as $c){
  echo "$c\n";
}
?>

这是我运行后显示的内容:

东京,墨西哥城,纽约市,孟买,首尔,上海,拉各斯,布宜诺斯艾利斯,开罗,伦敦,布宜诺斯艾利斯开罗拉各斯伦敦墨西哥城孟买纽约市首尔上海东京

1 个答案:

答案 0 :(得分:0)

您的代码排序很好,唯一的问题是新行。要使新行成为保留者\n,您需要将数据放在<pre>标记中。我建议使用<br>

如果您在控制台\n中运行它,则可以正常运行并且您的代码可以运行。你在排序之前和排序之后一次显示城市,所以我想这就是你混淆的地方。

<?php
$cities = array (
  "Tokyo",
  "Mexico City",
  "New York City",
  "Mumbai",
  "Seoul",
  "Shanghai",
  "Lagos",
  "Buenos Aires",
  "Cairo",
  "London" 
);

sort ($cities);

echo "<pre>";
foreach ($cities as $c) {
  echo "$c\n";
}
echo "</pre>";

foreach ($cities as $c) {
  echo "$c<br>";
}