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.
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);
}
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
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));
精彩评论