php - 引用 foreach 循环中的先前值
问题描述
我不完全确定如何措辞。我将首先向您展示代码/API
$ips = array("IP1", "IP2");
foreach ($ips as $ip) {
$location = get_geolocation($apiKey, $ip);
$decodedLocation = json_decode($location, true);
echo "<tr>";
echo "<td>".$decodedLocation['ip']."</td>";
echo "<td>".$decodedLocation['continent_name']." (".$decodedLocation['continent_code'].")</td>";
echo "<td>".$decodedLocation['country_name']." (".$decodedLocation['country_code2'].")</td>";
echo "<td>".$decodedLocation['organization']."</td>";
echo "<td>".$decodedLocation['isp']."</td>";
echo "<td>".$decodedLocation['languages']."</td>";
if($decodedLocation['is_eu'] == true) {
echo "<td>Yes</td>";
} else {
echo "<td>No</td>";
}
echo "<td>".$decodedLocation['currency']['name']."</td>";
echo "<td>".$decodedLocation['time_zone']['name']."</td>";
echo "</tr>";
}
我希望能够将 IP1 信息与 IP2 进行比较。例如,我想在循环后查看 IP1 的 Country Name 是否与 IP2 的 Country Name 匹配。
谢谢你。
解决方案
将最后一个值存储在变量中:
$ips = [ 'ip1', 'ip2' ];
$lastIp = null;
foreach ($ips as $ip) {
// Check if last ip is filled (on first iteration it will be null)
if ($lastIp) {
// Your logic using lastIp here
}
$lastIp = $ip;
}
推荐阅读
- javascript - 为什么我遇到错误找不到模块 protobufjs
- javascript - npx create-react-app myapp 不起作用。中止安装
- android - 如何以编程方式禁用 MDM 信息亭模式
- django - 使用 apache2 负载均衡器部署 Django 应用程序时无法访问静态文件
- javascript - CSS 添加第二个过渡
- javascript - 我创建了用于自动显示当前月份的 java,但我试图始终显示下个月。例如:如果六月 - 显示“七月”
- sql - 使用 codeigniter 将连接表中的列连接到另一列
- r - 如何pivot_longer 变量名称中包含整数和变量的数据框?
- reactjs - 我无法更改 setArray 的状态。我可以改变其他使用状态的状态,但不能改变这个
- javascript - 个人资料图片和生物输入更新