计算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屋!