Total number of repetition of array value in PHP
I have an开发者_如何学C array like:
[Organization_id] => Array
(
[0] => 4
[1] => 4
[2] => 2
[3] => 4
[4] => 2
[5] => 4
[6] => 4
[7] => 4
[8] => 2
)
Now i just want to know that how many times the vale '4' & '2' does present in this array ie: my result must be some thing like this:
[id_repeat] => Array
(
[0] => 6
[1] => 3
)
where, 0th location will represent the total number of repetition of value '4' & 1st location will represent the total number of repetition of value '2'.
But keep in mind that these values are not hardcoded these values will be come from some table.
Thanks in advance.
use array_count_values()
:
This function:
Returns an associative array of values from input as keys and their count as value.
Sample usage:
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
The above example will output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
You can do:
$freq_array = array_count_values($Organization_id);
$id_repeat = array(
$freq_array[4],
$freq_array[2]
);
Here is a code snippet that will create an array b
of frequencies of each elements in the input array a
in the order of their appearance in a
. Note that it doesn't count null
values in the input. It is in javascript as I'm not good at php.
var a = [4, 4, 2, 4, 2, 4, 3, 3, 3, 5 , 4];
var b = [];
for(var i = 0; i < a.length; i++)
{
if(a[i] != null)
b.push(1);
else
continue;
for(var j = i + 1; j < a.length; j++)
{
if(a[i] == a[j])
{
b[b.length - 1]++;
a[j] = null;
}
}
}
console.log(b.join());//5,2,3,1
精彩评论