我真的很感谢你的帮助。
我想在foreach中使用一个额外的数组。
目前它看起来像这样,效果很好。
<?php
$listcity = array("Negril" => "negril",
"Kingston" => "kingston",
"Ocho Rios" => "ocho-rios");
foreach ($listcity as $cityname => $citylink) {
echo "<li data-name=\"$cityname Hotels\"><a href=\"https://example.com/hotels/$citylink\">$cityname</a></li>";
}
?>
现在我想添加一个带有以下数字的范围:
$distancemiles = array("Negril" => "25",
"Kingston" => "10",
"Ocho Rios" => "67");
我希望最终的回声如下:
<li data-name=\"$cityname Hotels\"><a href=\"https://example/hotels/$citylink\">$cityname</a><span>(HERE THE DISTANCE IN MILES miles)</span></li>
以便浏览器输出例如:
所以我想知道如何组合我的三个数据源:
$ cityname - &gt;应该是城市的名称
$ citylink - &gt;应该是链接结束
$ distancetocity - &gt;应该是距离
有人会帮我这个吗?我努力工作并阅读各种在线教程,但我每次都失败了。
最佳,
最高
答案 0 :(得分:1)
您可以通过名称找到城市的距离。城市的$distancemiles[$cityname]
返回距离。
foreach ($listcity as $cityname => $citylink){
echo "<li data-name=\"$cityname Hotels\">
<a href=\"https://example.com/hotels/$citylink\">$cityname</a>
<span>$distancemiles[$cityname]</span>
</li>";
}
查看demo
中的代码结果答案 1 :(得分:1)
<?php
$listcity = array("Negril" => "negril",
"Kingston" => "kingston",
"Ocho Rios" => "ocho-rios");
$distancemiles = array("Negril" => "25",
"Kingston" => "10",
"Ocho Rios" => "67");
foreach ($listcity as $cityname => $citylink) {
echo "<li data-name=\"$cityname Hotels\"><a href=\"https://example/hotels/$citylink\">$cityname</a><span>($distancemiles[$cityname])</span></li>";
}
?>
您可以使用距离数组查找里程值。
您的数组列表城市数组具有结构cityname-&gt; linkname您的距离数组具有结构cityname-&gt; distanceInMiles,因此您可以使用for循环中的城市名称来查找城市名称索引处的距离。
答案 2 :(得分:1)
然后你可以这样做:
echo "<li data-name=\"$cityname Hotels\"><a href=\"https://example.com/hotels/$citylink\">$cityname</a><span>{$distancemiles[$cityname]}</span></li>";
答案 3 :(得分:1)
将您的数组合并为一个数组,然后按如下方式访问它:
$listcity = array("Negril" => "negril",
"Kingston" => "kingston",
"Ocho Rios" => "ocho-rios");
$distancemiles = array("Negril" => "25",
"Kingston" => "10",
"Ocho Rios" => "67");
$oneArray = array_merge_recursive($listcity, $distancemiles);
foreach ($oneArray as $cityname => $citylink) {
echo "<li data-name=\"$cityname Hotels\"><a href=\"https://example/hotels/".$citylink[0]."\">$cityname</a><span>".$citylink[1]."</span></li>";
}
答案 4 :(得分:0)
如果您添加$distancemiles
数组的引用并将$cityname
作为关键字(例如$distancemiles[$cityname]
),则可以获得foreach循环中的里程数。
$listcity = array(
"Negril" => "negril",
"Kingston" => "kingston",
"Ocho Rios" => "ocho-rios");
$distancemiles = array("Negril" => "25",
"Kingston" => "10",
"Ocho Rios" => "67");
foreach ($listcity as $cityname => $citylink) {
echo "<li data-name=\"$cityname Hotels\"><a href=\"https://example.com/hotels/$citylink\">$cityname</a><span>$distancemiles[$cityname]</span></li>";
}
// Negril25
// Kingston10
// Ocho Rios67