İşte konuyla benim bıçak bulunuyor
<pre>
<?php
class Thingy
{
protected $store;
protected $universe;
public function __construct( array $data )
{
$this->store = $data;
$this->universe = array_sum( $data );
}
public function reduceTo( $size )
{
// Guard condition incase reduction size is too big
$storeSize = count( $this->store );
if ( $size >= $storeSize )
{
return $this->store;
}
// Odd number of elements must be handled differently
if ( $storeSize & 1 )
{
$chunked = array_chunk( $this->store, ceil( $storeSize / 2 ) );
$middleValue = array_pop( $chunked[0] );
$chunked = array_chunk( array_merge( $chunked[0], $chunked[1] ), floor( $storeSize / $size ) );
// Distribute odd-man-out amonst other values
foreach ( $chunked as &$chunk )
{
$chunk[] = $middleValue / $size;
}
} else {
$chunked = array_chunk( $this->store, floor( $storeSize / $size ) );
}
return array_map( 'array_sum', $chunked );
}
}
$tests = array(
array( 2, array( 25, 50, 25 ) )
, array( 2, array( 10, 15, 20, 25 ) )
, array( 2, array( 10, 10, 10, 10, 11 ) )
, array( 6, array_fill( 0, 15, 1 ) )
);
foreach( $tests as $test )
{
$t = new Thingy( $test[1] );
print_r( $t->reduceTo( $test[0] ) );
}
?>
</pre>