1

how can i count the total duplicate link in the array?

its similar question here: count of duplicate elements in an array in php

but im not sure how to implement the code on my case. my server PHP version 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
        )
)

I am expecting the result to be:

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

3 Answers 3

3

You can simply use

$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

Sign up to request clarification or add additional context in comments.

2 Comments

@Uchiha it should count the total as well. how can i count the total?
@tonoslfx Try it out my answer they work for you or not?
2

Try below code:

<?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);
?>

Comments

1

You can use this simple logic :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.