data array
Array
(
[0] => Array
(
[1] => 7
)
[1] => Array
(
[2] => 7
)
[2] => Array
(
[3] => 7
)
[3] => Array
(
[4] => 7
)
[4] => Array
(
[4] => 7
)
[5] => Array
(
[5] => 7
)
[6] => Array
(
[5] => 7
)
[7] => Array
(
[6] => 7
)
[8] => Array
(
[1] => 8
)
[9] => Array
(
[2] => 8
)
)
Final result
$fianl = array(
'7' => 6,
'8' => 2
);
Question: I have one array will store the duplicate value data then need to be loop the array to find out the total count number by the value id, it's will not be count if the same value have count before. I stuck in this logic for quite some times :(. Does anyone can help me.
CodePudding user response:
$arr = [ [ 7 ], [ 7 ], [ 7 ], [ 7 ], [ 7 ], [ 7 ], [ 7 ], [ 7 ], [ 8 ], [ 8 ] ];
$result = array_count_values(array_column(array_values($arr), 0));
print_r($result);
Output:
Array
(
[7] => 8
[8] => 2
)
CodePudding user response:
<?php
$values = [
[1 => 7],
[2 => 7],
[3 => 7],
[4 => 7],
[4 => 7],
[5 => 7],
[5 => 7],
[6 => 7],
[1 => 8],
[2 => 8],
];
foreach($values as $arr) {
$items[reset($arr)][] = key($arr);
}
$items = array_map('array_unique', $items);
$result = array_map('count', $items);
var_export($result);
Output:
array (
7 => 6,
8 => 2,
)
You can loop through your original array, and build sub arrays with the values as keys and the keys as values. Then filter out duplicates, and count.
You may want to dump the $items
array before the array_map
, to see the data structure, before filtering and counting.