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?

5
  • 1
    Can you check if the array values match exactly with the matrix? For example I cannot see 2 in the array. Commented Sep 6, 2013 at 13:02
  • 1
    You want a run length encoding? Commented Sep 6, 2013 at 13:03
  • ^@fedorqui & no 4 either. Commented Sep 6, 2013 at 13:04
  • The numbers are completely random and the check should only be done with addjecent numbers Commented Sep 6, 2013 at 13:05
  • He's counting the amount of times the number is the same, before the number changes. Commented Sep 6, 2013 at 13:06

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.