简体   繁体   中英

Iterate through a php multi dimensional array with specific condition

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

Effectively you have a list of employees with their training listed in a comma separated list ?

So basically you need to iterate through the list stripping out the information you require (company & training). Then every time you get a match you increment the matching data.

There are a few ways to do this the simplest would be to iterate through the results to create an array which looks something like...

$countArray = [
    "Alucam" => [
        "ELECTRICAL SAFETY TRAINING" = 2,
    ],
];

The code would look like:

$countArray = [];

// Generate the array
foreach ($array as $employee) {
    $trainingList = array_map("trim", explode(",", $employee["training"]));
    foreach ($trainingList as $training) {
        $countArray[$employee["company"]][$training] = ($countArray[$employee["company"]][$training] ?? 0)  + 1;
    }
}


// Generate the output
foreach ($countArray as $companyName => $training) {
    foreach ($training as $trainingName => $trainingCount) {
        echo "{$trainingCount} {$companyName} did {$trainingName}", PHP_EOL;
    }
}

/*

Output:

2 ALUCAM did ELECTRICAL SAFETY TRAINING
1 US EMBASSY did FORKLIFT
1 US EMBASSY did JLG SCISSOR LIFT
1 US EMBASSY did AERAL PLATFORM

*/

However, this does mean you can have "unusual" characters in array keys which could lead to problems further down the line. So you may do better with a slightly more complicated approach (ie having index arrays for the company and training names) which gives an array a little something like...

$countArray = [
    'company' => [
        0 => 'ALUCAM',
        1 => 'US EMBASSY',
    ],
    'training' => [
        0 => 'ELECTRICAL SAFETY TRAINING',
        1 => 'FORKLIFT',
        2 => 'JLG SCISSOR LIFT',
        3 => 'AERAL PLATFORM',
    ],
    'count' => [
        0 => [
            0 => 2,
        ],
        1 => [
            1 => 1,
            2 => 1,
            3 => 1,
        ],
    ],
];

The code would look like:

// Generate the array
foreach ($array as $employee) {
    if (false === ($companyIndex = array_search($employee["company"], $countArray["company"]))) {
        $companyIndex = count($countArray["company"]);
        $countArray["company"][] = $employee["company"];
    }

    $trainingList = array_map("trim", explode(",", $employee["training"]));
    foreach ($trainingList as $training) {
        if (false === ($trainingIndex = array_search($training, $countArray["training"]))) {
            $trainingIndex = count($countArray["training"]);
            $countArray["training"][] = $training;
        }
        $countArray["count"][$companyIndex][$trainingIndex] = ($countArray["count"][$companyIndex][$trainingIndex] ?? 0) + 1;
    }
}


// Generate the output
foreach ($countArray["count"] as $companyKey => $companyCount) {
    $companyName = $countArray["company"][$companyKey];
    foreach ($companyCount as $trainingKey => $trainingCount) {
        $trainingName = $countArray["training"][$trainingKey];
        echo "{$trainingCount} {$companyName} did {$trainingName}", PHP_EOL;
    }
}

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

You can use array_count_values and array_column to achieve something like this: You can modify as required.

    $arr = [
            ['date_creation' => 'Apr 10, 2021 10:17 pm', 'idformation' => 84,       'idsociete' => 7, 'training' => 'ELECTRICAL SAFETY TRAINING', 'company' => 'ALUCAM'],
            ['date_creation' => 'Apr 10, 2021 10:17 pm', 'idformation' => 84, 'idsociete' => 7, 'training' => 'ELECTRICAL SAFETY TRAINING', 'company' => 'ALUCAM'],
            ['date_creation' => 'Apr 12, 2021 03:27 pm', 'idformation' => 104, 'idsociete' => 201, 'training' => 'FORKLIFT, JLG SCISSOR LIFT, AERAL PLATFORM', 'company' => 'US EMBASSY'],
    ];

    $training = 'ALUCAM';
    
    $companies = array_count_values(array_column($arr, 'company'))[$training]; // outputs: 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM