转换维数组到一个二维数组的元素计数 [英] Converting 1D array to a 2D array with count of elements

查看:101
本文介绍了转换维数组到一个二维数组的元素计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我卡住了,我想知道,如果有人能在正确的方向指向我。

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

我试过遍历$启动阵列,但我被困旁观起来$开始第n-1,而无需关键。

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

这篇关于转换维数组到一个二维数组的元素计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆