PHP计数重复的总链接

时间:2015-10-08 12:18:14

标签: php multidimensional-array

如何计算数组中的重复链接总数?

此处的类似问题:count of duplicate elements in an array in php

但我不知道如何在我的案例中实现代码。 我的服务器PHP版本5.4

Array
(
    [0] => Array
        (
            [link] => http://myexample.com
            [total] => 3
        )

    [1] => Array
        (
            [link] => http://myexampledomain.com
            [total] => 2
        )

    [2] => Array
        (
            [link] => http://myexample.com
            [total] => 1
        )
)

我期待结果是:

http://myexample.com: 4
http://myotherdomain.com: 2

3 个答案:

答案 0 :(得分:3)

您只需使用

即可
$result = [];
array_walk($arr, function($v, $k)use(&$result) {
    if (isset($result[$v['link']])) {
        $result[$v['link']] += $v['total'];
    }else{
        $result[$v['link']] = $v['total'];
    }
});
print_r($result);

Demo

答案 1 :(得分:2)

尝试以下代码:

<?php
$array = array(array("link" => "http://myexample.com", "total" => 3), array("link" => "http://myexampledomain.com", "total" => 2), array("link" => "http://myexample.com", "total" => 1));
$res = array();
foreach ($array as $vals) {
    if (array_key_exists($vals['link'], $res)) {
        $res[$vals['link']]+=$vals['total'];
    } else {
        $res[$vals['link']]=$vals['total'];
    }
}
print_r($res);
?>

答案 2 :(得分:1)

您可以使用这个简单的逻辑:

$tempArray = array();
foreach ($array as $value) {
    if (!array_key_exists($value['link'],$tempArray) {
        $tempArray[$value['link']] = 1;
    } else {
        $tempArray[$value['link']] = $tempArray['link'] + 1;
    }
}

print_r($tempArray);