douqian9729 2018-04-19 21:39
浏览 36
已采纳

使用范围val组织数组

I’m working on an array of numeric values.

I have a array of numeric values as the following in PHP

array('85kg' => '1', '87kg' => '3', '88kg' => '1', '90kg' => '3', '98kg' => '1')

And I’m trying to convert it into range for e.g in above case it would be:

array('85kg-88kg' => '5', '89kg-92kg' => '3', '97kg-100kg' => '1')

Range 3kg any key.. I don’t have any idea how to convert it into range.

  • 写回答

1条回答 默认 最新

  • duangua5308 2018-04-19 22:28
    关注

    You could get the first key, and last key as integer using cast ((int)). Then, you could create a loop from the first key, until you reach the last key. Inside it, you could loop over the initial array and check if the key is inside the range. If so, you could append the current value to the final array:

    $arr = array('85kg' => '1', '87kg' => '3', '88kg' => '1', '90kg' => '3', '98kg' => '1');
    $first_key = (int)key($arr); // 85
    end($arr); // move to the last element to get the last key,
    $last_key = (int)key($arr); // 98
    $it = $first_key;
    while ($it <= $last_key) { // from 85 - 98
        foreach ($arr as $key => $val) {
            $intk = (int)$key ; // 85, 87, 88, 90, 98
            if ($intk >= $it && $intk <= $it +3) { 
                $arrk = $it.'kg-'.($it+3).'kg'; // create key
                if (!isset($out[$arrk])) $out[$arrk] = 0; // create key in array
                $out[$arrk] += $val ; // append value
            }
        }
        $it += 4; // += 3 + 1 (new weight)
    }
    print_r($out);
    

    Will outputs:

    Array
    (
        [85kg-88kg] => 5
        [89kg-92kg] => 3
        [97kg-100kg] => 1
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧