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

时间:2021-03-23 12:18:18

I have an array like:

我有一个像:

array[
  '5' => 142,
  '2' => 57,
  '18' => 37
];

I need to split this array into bunch of 50 so the output would be:

我需要将此数组拆分为50个,因此输出将为:

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

Can someone help to provide some solution or logic or any existing function in PHP?

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

2 个解决方案

#1


2  

just mind games

只是介意游戏

$line = [];
// Invert array
foreach($arr as $k=>$v) {
   $line = array_merge($line, array_fill(0, $v, $k));
}
// Split and count occurrences
$res = array_map('array_count_values', array_chunk($line, 50));
print_r($res);

demo

#2


1  

You could try something like this :

你可以尝试这样的事情:

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

Outputs :

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

#1


2  

just mind games

只是介意游戏

$line = [];
// Invert array
foreach($arr as $k=>$v) {
   $line = array_merge($line, array_fill(0, $v, $k));
}
// Split and count occurrences
$res = array_map('array_count_values', array_chunk($line, 50));
print_r($res);

demo

#2


1  

You could try something like this :

你可以尝试这样的事情:

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

Outputs :

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