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?
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;
}
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.