计算php中关联数组中值的出现次数 [英] count occurrences of values in an associative array in php
问题描述
请帮助我如何计算此关联数组中值的出现次数.
Please help me on how to count the occurrences of value in this associative array.
<?php
$employees = array(
1 => array(
'name' => 'Jason Alipala',
'employee_id' => 'G1001-05',
'position' => 1
),
2 => array(
'name' => 'Bryann Revina',
'employee_id' => 'G1009-03',
'position' => 2
),
3 => array(
'name' => 'Jeniel Mangahis',
'employee_id' => 'G1009-04',
'position' => 2
),
4 => array(
'name' => 'Arjay Bussala',
'employee_id' => 'G1009-05',
'position' => 3
),
5 => array(
'name' => 'Ronnel Ines',
'employee_id' => 'G1002-06',
'position' => 3
)
);
?>
这是我来自 fake_db.php 的代码,我在 index.php 中include_once.我想计算位置"相同值的出现次数..例如1 = 1, 2 = 2, 3 = 2
This is my code from fake_db.php which I include_once in the index.php. I want to count the occurrences of the same value of 'position'.. e.g. 1 = 1, 2 = 2, 3 = 2
此外,还有一个名为 $positions 的数组...
in addition, there is another array named $positions...
$positions = array(
1 => 'TL',
2 => 'Programmer',
3 => 'Converter');
这个数组是我比较 $employees 数组中的位置"的地方.
this array is where i compare the 'position' from the $employees array.
感谢任何帮助,谢谢!
推荐答案
array_count_values
& 的组合array_column
(PHP 5 >= 5.5.0, PHP 7) 应该可以工作 -
Combination of array_count_values
& array_column
(PHP 5 >= 5.5.0, PHP 7) should work -
$counts = array_count_values(
array_column($employees, 'position')
);
输出
array(3) {
[1]=>
int(1)
[2]=>
int(2)
[3]=>
int(2)
}
更新
$final = array_filter($counts, function($a) {
return $a >= 2;
});
输出
array(2) {
[2]=>
int(2)
[3]=>
int(2)
}
这篇关于计算php中关联数组中值的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!