Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

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           
   )
   );

?>

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

in addition, there is another array named $positions...

$positions = array(
    1 => 'TL',
    2 => 'Programmer',
    3 => 'Converter');

this array is where i compare the 'position' from the $employees array.

any help is appreciated, thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Combination of array_count_values & array_column (PHP 5 >= 5.5.0, PHP 7) should work -

$counts = array_count_values(
    array_column($employees, 'position')
);

Output

array(3) {
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(2)
}

Update

$final = array_filter($counts, function($a) {
   return $a >= 2;
});

Output

array(2) {
  [2]=>
  int(2)
  [3]=>
  int(2)
}

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...