1

I'm stuck and am wondering if someone could point me in the right direction.

I have an array containing numbers, eg:

$start = array(0,0,0,45,45,0,3,0,0,1,1,1,1);

And would like that array to convert to this array:

$result = array( array('id'=>0, 'aantal'=>3,
                 array('id'=>45,'aantal'=>2),
                 array('id'=>0, 'aantal'=>1),
                 array('id'=>3,'aantal'=>1),
                 array('id'=>0, 'aantal'=>1),
                 array('id'=>1,'aantal'=>4)
                )

I tried traversing the $start array, but I got stuck onlooking up the n-1 in $start without having the key.

Does anyone have any advice on how I can do this?

Nicholas Post
  • 1,857
  • 1
  • 18
  • 31
stUrb
  • 6,612
  • 8
  • 43
  • 71

1 Answers1

1

This would be the typical approach for run length encoding an array of items:

$array = array(0,0,0,45,45,0,3,0,0,1,1,1,1);
$last = null;
$current = null;

$result = array();

foreach ($array as $item) {
    if ($item == $last) {
        // increase frequency by 1
        ++$current['aantal'];
    } else {
        // the first iteration will not have a buffer yet
        if ($current) {
            $result[] = $current;
        }
        // create buffer array item, set frequency to 1
        $current = array('id' => $item, 'aantal' => 1);
        $last = $item;
    }
}
// last pass
if ($current) {
    $result[] = $current;
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309