Page MenuHomeDevCentral

Methods to count by and group by arrays
Open, WishlistPublic

Description

Two general interest functions could be moved from rTOOLS to rKOT:

Current code

Methods from infographics/parlement-fr.php
/**
 * Gets a count of items, grouped a key.
 *
 * This achieves the same result than SQL queries like:
 * SELECT foo, COUNT(foo) AS c FROM quux GROUP BY foo ORDER BY c DESC;
 *
 * @param $array an array, each line being an array
 * @param $by the grouping key
 * @return $array an array, each line having the key value as key, and the count as value
 */
function count_by ($array, $by) {
    $count = [];

    foreach ($array as $row) {
        $key = $row[$by];
        if (isset($count[$key])) {
            $count[$key]++;
        } else {
            $count[$key] = 1;
        }
    }
    arsort($count, SORT_NUMERIC);

    return $count;
}

/**
 * Gets a group of items' property, grouped by a key
 *
 * @param $array an array, each line being an array
 * @param $by the grouping key
 * @return $array an array, each element an array of properties matching the key.
 */
function group_by($array, $by, $property) {
    $groups = [];

    foreach ($array as $row) {
        $key = $row[$by];
        $groups[$key][] = $row[$property];
    }
    ksort($groups, SORT_NUMERIC);

    return $groups;
}

Current use

Example of use from infographics/parlement-fr.php
$count = count_by($senateurs, 'born');
$data = [];
foreach ($count as $key => $value) {
    $data[] = "[$key, $value]";
}
var senateurs = <?= json_encode(group_by($senateurs, 'born', 'name')); ?>;

Example of use in ...\Collection\OmniArray

Example of use we could offer
<?php
$countOfSenateursByYear = HashMap::from($senateurs)
    ->countBy('born')
    ->map(fn($key, $value) => "[$key, $value]")
    ->toArray();
<?= HashMap::from($senateurs)->groupBy('born', 'name')->toJSON() ?>

The last example would benefit from:

public function toJSON () : string {
    return json_encode($this->map);
}

Event Timeline

dereckson triaged this task as Wishlist priority.Jan 25 2020, 08:18
dereckson created this task.
dereckson moved this task from Backlog to Dev on the good-first-issue board.