首页 > 解决方案 > 引用 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 匹配。

谢谢你。

标签: phpforeach

解决方案


将最后一个值存储在变量中:

$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;
}

推荐阅读