Tengo valores 1,2,3 y creará otro valor como el siguiente y producirá resultados al sumar. Como hay 3 valores, creará tres matrices. si fueran 5 valores, entonces se requieren 5 matrices de este tipo.
1 2 3 1 2 3 1 2 3 Result is : 1 3 6 5 3Lo que estoy haciendo es:
$a=[1,2,3]; $b=$a; $c=$a; $d=[]; array_push($a,0,0); array_unshift($b,0); array_push($b,0); array_unshift($c,0,0); $d = array_map(function () { return array_sum(func_get_args()); }, $a,$b,$c); print_r($d);No puedo encontrar la manera de hacer esto para más valores que 3 y dinámicamente. Entonces solo tengo que poner los valores y me da el resultado. No estoy pidiendo el código, pero puede ayudarme con eso, cómo debo abordarlo. Gracias.
Recomiendo un enfoque lineal sin preparativos, relleno o exceso de datos.
Use los índices y la aritmética simple para agregar valores a su elemento deseado en la salida.
Código: ( Demostración )
$array = range(1, 3); $result = []; foreach ($array as $shifter => $unused) { foreach ($array as $index => $value) { $key = $shifter + $index; $result[$key] = ($result[$key] ?? 0) + $value; } } var_export($result); // [1, 3, 6, 5, 3]Esto es muy limpio, legible, fácil de mantener y más eficiente.
Mientras $shifter = 0 , $key será 0 , 1 y luego 2 ; formando [1, 2, 3] .
Mientras $shifter = 1 , $key será 1 , 2 y luego 3 ; formando [1, 3, 5, 3] .
Mientras $shifter = 2 , $key será 2 , 3 y luego 4 ; formando [1, 3, 6, 5, 3] .
Si está usando PHP 7.4+, puede usar lo siguiente...
// Ensure the keys are indexed not associative. $input = array_values( [ 1, 2, 3, 4, 5 ] ); // Create rows. $rows = []; foreach ( $input as $key => $value ) { $rows[ $key ] = array_merge( array_fill( 0, $key, 0 ), $input ); } // Sum values. $output = array_map( function() { return array_sum( func_get_args() ); }, ...$rows );Si está utilizando una versión de PHP inferior a 7.4, puede hacer...
// Ensure the keys are indexed not associative. $input = array_values( [ 1, 2, 3 ] ); // Create rows. $rows = []; foreach ( $input as $key => $value ) { $rows[ $key ] = array_merge( array_fill( 0, $key, 0 ), $input ); } // Sum values. $output = call_user_func_array( 'array_map', array_merge( [ function() { return array_sum( func_get_args() ); } ], $rows ) );Estoy pensando que usar un desplazamiento tiene sentido, es lo mismo que su enfoque, excepto que estoy agregando un 0 usando array_fill
$arr = [1,2,3]; $result = []; $offset = 0; for($i = 0; $i < count($arr); $i++) { $result = array_map(function () { return array_sum(func_get_args()); }, $result, array_merge(array_fill(0, $offset, 0), $arr)); $offset++; } var_dump($result);La ventaja de usar esto es que usa muy poca memoria incluso para una matriz inicial muy grande.