根据值将数组拆分为相同大小的数组

时间:2018-02-09 10:16:29

标签: php arrays arraylist

我有一个像:

这样的数组
array[
  '5' => 142,
  '2' => 57,
  '18' => 37
];

我需要将这个数组分成50个串,所以输出为:

array[
  '0' => ['5' => 50],
  '1' => ['5' => 50],
  '2' => ['5' => 42, '2' => 8],
  '3' => ['2' => 49, '18' => 1],
  '4' => ['18' => 36],
];

有人可以帮助在PHP中提供某些解决方案或逻辑或任何现有功能吗?

2 个答案:

答案 0 :(得分:2)

只是介意游戏

Page<Record> findByCycle_IdAndUserId(Long cycleId, Long userId, Pageable pageable);

demo

答案 1 :(得分:1)

您可以尝试这样的事情:

$total = [] ; $ckey = 0 ; 
foreach ($array as $key => $value) {
    while ($value) {
        $cursum = isset($total[$ckey]) ? array_sum($total[$ckey]) : 0 ;
        if ($cursum == 50) $ckey++ ;

        if ($value + $cursum > 50) $add = 50 - $cursum ;
        else  $add = $value ;

        $total[$ckey][$key] = $add ;
        $value -= $add ;
    }
}
print_r($total) ;

输出:

Array (
    [0] => Array (
            [5] => 50
        )

    [1] => Array (
            [5] => 50
        )

    [2] => Array (
            [5] => 42
            [2] => 8
        )

    [3] => Array (
            [2] => 49
            [18] => 1
        )

    [4] => Array (
            [18] => 36
        )
)