I have a php array below and i want to know how to get number of companies who did a training course. Look below:
Array ( [0] => Array ( [date_creation] => Apr 10, 2021 10:17 pm [idformation] => 84 [idsociete] => 7 [training] => ELECTRICAL SAFETY TRAINING [company] => ALUCAM ) [1] => Array ( [date_creation] => Apr 10, 2021 10:55 pm [idformation] => 84 [idsociete] => 7 [training] => ELECTRICAL SAFETY TRAINING [company] => ALUCAM ) [2] => Array ( [date_creation] => Apr 12, 2021 03:27 pm [idformation] => 104 [idsociete] => 201 [training] => FORKLIFT, JLG SCISSOR LIFT, AERAL PLATFORM [company] => US EMBASSY ) );
Each array represents the record of a worker in the database from a company say Alucam and did training Electrical safety.
So from the array above i want to get something like:
2 Alucams did electrical safety as seen in the array.
I just need a clue on how to get the count of persons who did a particular training from the array.
Please help
Advertisement
Answer
I assume you can have the same training from different companies, opposite case you can simplified the code.
Input data (I simplified your input array, including only the fields I need):
$workers = array(array("training" => "ELECTRICAL SAFETY TRAINING", "company" => "ALUCAM"), array("training" => "ELECTRICAL SAFETY TRAINING", "company" => "ALUCAM"), array("training" => "FORKLIFT, JLG SCISSOR LIFT, AERAL PLATFORM", "company" => "US EMBASSY"), array("training" => "FORKLIFT, JLG SCISSOR LIFT, AERAL PLATFORM", "company" => "ALUCAM") );
Php code:
$trainingCount = array(); foreach($workers as $worker) { $training = $worker["training"]; $company = $worker["company"]; if(! array_key_exists($training, $trainingCount)) { $trainingCount[$training] = array(); } if(! array_key_exists($company, $trainingCount[$training])) { $trainingCount[$training][$company] = 0; } $trainingCount[$training][$company]++; }
Result:
array('ELECTRICAL SAFETY TRAINING' => array('ALUCAM' => 2), 'FORKLIFT, JLG SCISSOR LIFT, AERAL PLATFORM' => array('US EMBASSY' => 1, 'ALUCAM' => 1));