0

How can we find the count of duplicate elements in a multidimensional array,

I have an array like this:

Array 
      ( 
          [0] => Array 
              ( 
                  [brti] => 29 
              ) 
          [1] => Array 
              ( 
                  [voda] => 6 
              ) 
          [2] => Array 
              ( 
                  [btel] => 8 
              ) 
          [3] => Array 
              ( 
                  [btel] => 10 
              ) 
      )

Question: How to simplify the structure of array, i mean can be counting the value if there is indicate that have same key ?

just like this:

Array 
  ( 
      [0] => Array 
          ( 
              [brti] => 29 
          ) 
      [1] => Array 
          ( 
              [voda] => 6 
          ) 
      [2] => Array 
          ( 
              [btel] => 18 
          ) 
  )

So far, i've tried this way, but it didn't help me. My array is store in $test

    $test = [sample array]

    $count = array();
    foreach ($test as $key => $value) {
        foreach ($value as $k => $val) {
            if (isset($count[$val])) {
                ++$count[$val];
            } else {
                $count[$value] = 1;
            }
        }
    }
    print_r($count);
4
  • you also want to sum the value of duplicate key... which you haven't mention but can be seen clear in your example Commented Feb 20, 2019 at 9:56
  • What do you mean by "simplified"? Commented Feb 20, 2019 at 9:56
  • Yes sir, i mean simplified with sum the value of same key @SayedMohdAli Commented Feb 20, 2019 at 9:57
  • i mean simplified with sum the value of same key @YongQuan Commented Feb 20, 2019 at 9:57

2 Answers 2

1
<?php

$array = [
    "0" => ["brti" => 29],
    "1" => ["voda" => 6],
    "2" => ["btel" => 8],
    "3" => ["btel" => 10],
];
$final = array();

array_walk_recursive($array, function($item, $key) use (&$final){
    $final[$key] = isset($final[$key]) ?  $item + $final[$key] : $item;
});
print_r($final);

    });

check demo

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

Comments

0

You can do it in very simple way,

$test = [];
foreach ($array as $value)
{
    foreach ($value as $k => $v)
    {
        // $test[$k] = ($test[$k] ?? 0); // initialised if not php 7+
        $test[$k] = (empty($test[$k]) ? 0: $test[$k]); //  below php 7 
        $test[$k] += $v;
    }
}

print_r($test);

Output:

Array
(
    [brti] => 29
    [voda] => 6
    [btel] => 18
)

Working demo.

2 Comments

Parse error, syntax error, unexpected '??' sir @Rahul Meshram
Check now. that was syntax of php 7+, you might be using php 7 below.

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.