ntan
ntan

Reputation: 2205

matching sub arrays on array and count them

i am having an array

 Array
(
    [1] => Array
        (
            [0] => 1
            [1] => 3
        )

    [2] => Array
        (
            [0] => 1
            [1] => 2
        )

    [3] => Array
        (
            [0] => 1
            [1] => 3
        )

)

and i need to find the common subarrays

In the above example array 1 and 3 have the common sub array

(
   [0] => 1
   [1] => 3
)

So the final array must be

    Array
(
    [1] => Array
        (
            [0] => 1
            [1] => 3
        )

    [2] => Array
        (
            [0] => 1
            [1] => 2
        )
)

But i need to count the common values some how.

Any suggestion.

Upvotes: 0

Views: 527

Answers (3)

mickmackusa
mickmackusa

Reputation: 47894

To isolate unique rows, use the SORT_REGULAR flag with array_unique().

To acquire the number of duplicated rows, subtract the unique count from the initial count.

Code: (Demo)

$array = [[1, 3], [1, 2], [1, 3]];
$count = count($array);
$unique = array_unique($array, SORT_REGULAR);
echo "Number of duplicated rows: " . ($count - count($unique));

Upvotes: 1

Russell Davis
Russell Davis

Reputation: 8528

I wouldn't use this for production code, but here's a quick & somewhat clever way to do it:

$arrays = array(array(1,3), array(1,2), array(1,3)); // Your example data

$serialized = array_map('serialize', $arrays);
$counts = array_count_values($serialized);
foreach ($counts as $data => $count) {
  echo "$count: " . print_r(unserialize($data), true);
}

Upvotes: 3

aWebDeveloper
aWebDeveloper

Reputation: 38352

Just compare each element of array with other assuming them as a linear array but use array_diff to compare each element. If they are different copy the element or array index into another array

Upvotes: 1

Related Questions