Marc Ermshaus’ avatar

Marc Ermshaus

Linkblog

Algorithmic Advent: 04 – Easy grouping with array_reduce and closures

Published on 4 Dec 2010. Tagged with php, algorithmicadvent.

The built-in array_reduce function (documented here) can be used to group data so that it will be easier to work with in a view script. The same functionality can be achieved with a foreach loop, but I think it's a good possibility to demonstrate a non-obvious application for one of PHP's lesser-used array functions. Apart from that, the usage of closures and generally a more function-centered approach to programming always feel nicer to me.

$a = array (
    array('date' => '2010-06-11', 'title' => 'The Shawshank Redemption'),
    array('date' => '2010-06-11', 'title' => 'The Godfather'),
    array('date' => '2011-07-02', 'title' => 'Il buono, il brutto, il cattivo'),
    array('date' => '2011-07-02', 'title' => 'Pulp Fiction'),
    array('date' => '2011-03-28', 'title' => 'Inception'),
    array('date' => '2011-02-15', 'title' => '12 Angry Men'),
);

// Sort by date
usort($a, function($v, $w) {
    return strcmp($w['date'], $v['date']);
});

// Group by year, month and day
$new = array_reduce($a, function($newArray, $tmp) {
    list($y, $m, $d) = sscanf($tmp['date'], '%d-%d-%d');
    $newArray[$y][$m][$d][] = $tmp['title'];
    return $newArray;
}, array());

print_r($new);