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!
It is pretty simple. The array
$employees
is the array you have supplied. You can use this code:This gives the output:
array_column — Return the values from a single column of array. array_count_values — Counts all the values of an array.
Output
Nested loop will do the job. Take an array, keep the key as the actual value and the value in the key as COUNTER of that key. if the key exists in array that means it has the value just increment else assign 1 to initialize the key with value 1.
e.g. 1=>counter of 1 (occurrences)
These codes are inside a function that is called on every iteration of a foreach loop(another array named '$positions').. $key is a variable that contains value from that foreach loop (the '$positions' array).. this is what I've done, and it works for me. But i don't know if this is the proper way?
You can use array_count_value() pre-define php function to get your aim. you can see result here
Combination of
array_count_values
&array_column
(PHP 5 >= 5.5.0, PHP 7) should work -Output
Update
Output
Demo