1

I need to count the same values in multidimensional array and remove the duplicates.

My array:

$r = [
    ['a','b'],
    ['a','b'],
    ['c','d'],
    ['c','d'],
    ['c','d'],
    ['e','f'],
];

Need to output:

[0] => Array
    (
        [0] => a
        [1] => b
        [1] => 2 // Result
    )

[1] => Array
    (
        [0] => c
        [1] => d
        [1] => 3 // Result
    )

[2] => Array
    (
        [0] => e
        [1] => f
        [1] => 1 // Result
    )

I will be very grateful for your help.

4
  • I have tried but to no avail Commented Dec 25, 2016 at 11:54
  • "What" have you tried, exactly? Share the code you've got so far, even if it doesn't work. Commented Dec 25, 2016 at 11:56
  • stackoverflow.com/a/41275759/6521116 Commented Dec 25, 2016 at 12:03
  • I don't think your output can with the same key 1. Commented Dec 25, 2016 at 12:39

2 Answers 2

2
<?php
$r = [
    ['a','b'],
    ['a','b'],
    ['c','d'],
    ['c','d'],
    ['c','d'],
    ['e','f'],
];
foreach($r as $arr)
{
  $o[implode(',', $arr)][] = 1;
}
$output = [];
array_walk($o, function($v, $k) use(&$output){
    $output[] = array_merge(explode(',', $k), [count($v)]);
});
var_dump($output);

and the output:

array(3) {
  [0]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    int(2)
  }
  [1]=>
  array(3) {
    [0]=>
    string(1) "c"
    [1]=>
    string(1) "d"
    [2]=>
    int(3)
  }
  [2]=>
  array(3) {
    [0]=>
    string(1) "e"
    [1]=>
    string(1) "f"
    [2]=>
    int(1)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0
foreach ( $result1 as $key ):
    $o[implode(', ', $key)][] = null;
     foreach ($o as $key1) {
        $g[implode(', ', $key)] = count($key1);
    }
endforeach;
print_r($g);

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.