将 1D 数组转换为包含元素计数的 2D 数组


Converting 1D array to a 2D array with count of elements

我被困住了,想知道是否有人可以指出我正确的方向。

我有一个包含数字的数组,例如:

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

并希望该数组转换为此数组:

$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)
                )

我尝试遍历$start数组,但我在没有钥匙的情况下无法在$start中查找 n-1。

有人对我如何做到这一点有任何建议吗?

这是对项目数组进行运行长度编码的典型方法:

$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;
}