使用数字索引迭代并计算数组中的唯一值?

Iterate and count unique values from array with numerical index?

我有以下数组:

Array
(
    [0] => Array
        (
            [url] => https://website1.com/
            [remote_address] => Array
                (
                    [ip] => 1.1.1.1
                    [port] => 443
                )

        [headers] => Array
            (
                [date] => Mon, 31 Jan 2022 11:16:30 GMT
                [content-type] => text/html
            )

    )

[1] => Array
    (
        [url] => https://www.website1.com/
        [remote_address] => Array
            (
                [ip] => 1.1.1.1
                [port] => 443
            )

        [headers] => Array
            (
                [date] => Mon, 31 Jan 2022 11:16:30 GMT
                [content-encoding] => gzip
            )

    )

[2] => Array
    (
        [url] => https://www.website2.com/
        [remote_address] => Array
            (
                [ip] => 2.2.2.2
                [port] => 443
            )

        [headers] => Array
            (
                [date] => Mon, 31 Jan 2022 11:16:30 GMT
                [content-encoding] => br
            )

    )

[3] => Array
    (
        [url] => https://www.website3.com/
        [remote_address] => Array
            (
                [ip] => 3.3.3.3
                [port] => 443
            )

        [headers] => Array
            (
                [date] => Mon, 31 Jan 2022 11:16:30 GMT
                [content-encoding] => br
            )

    )

[4] => Array
    (
        [url] => https://www.website2.com/
        [remote_address] => Array
            (
                [ip] => 2.2.2.2
                [port] => 443
            )

        [headers] => Array
            (
                [date] => Mon, 31 Jan 2022 11:16:30 GMT
                [content-encoding] => gzip
            )

    )

[5] => Array
    (
        [url] => https://www.website4.com/
        [remote_address] => Array
            (
                [ip] => 4.4.4.4
                [port] => 443
            )

        [headers] => Array
            (
                [date] => Mon, 31 Jan 2022 10:44:46 GMT
                [content-encoding] => gzip
            )

    )
)

使用PHP (7.4) 我怎样才能对数组进行交互,找到所有 IP:s 然后计算唯一的 IP:s 不是数组中的第一个 IP?正确知道我在尝试迭代时有点迷路,也许我在考虑多维数组?

不应包含在计数中的“母”IP 可以作为变量从该数组外部获取。

感谢任何帮助,谢谢。

所以你的问题似乎是你不知道如何遍历数组。

这里一个简单的 foreach 循环就足够了

// init the array to hold the ips and their counts.
$ips = [];

foreach( $bigArray as $inner ) {
    $ip = $inner['remote_address']['ip']
    if ( array_key_exists($ip, $ips) ) {
        // we saw this IP before, so add 1 to count
        $ips[$ip]['count']++;
    } else {
        // first time we saw this ip, create entry in ips array with count of zero
        $ips[$ip] = ['count' => 0];
    }
}
print_r($ips);

这解决了不计算 ip 的第一次出现的情况,如果你想计算那个也只需从 1 而不是 0 开始计数器。