Created
April 5, 2022 21:31
-
-
Save sergioatanacio/9cdc4fa0d6cd70c1b56b340722d12d58 to your computer and use it in GitHub Desktop.
El objetivo es convertir un array en un string en php, ya que no he encontrado otra manera.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $array_aplanar = | |
| [ | |
| 'primero', | |
| 'segundo' => | |
| [ | |
| 'uno' => | |
| [ | |
| 'numero uno', 'numero dos', 'numero tres', 1.5, false | |
| ], | |
| 'dos', | |
| 'tres', | |
| ], | |
| 'tercero', | |
| ]; | |
| $array_reduce_key = function(array $array, callable $callback, $initial = []) | |
| { | |
| $carry = $initial; | |
| foreach($array as $key => $value){ | |
| $carry = $callback($carry, $key, $value); | |
| } | |
| return $carry; | |
| }; | |
| /* El objetivo del array es imprimir un string con los datos que se les pase como un string, para así poder | |
| imprimir un array y luego este array impreso, poderse usar con un copia y pega. */ | |
| $write_array = function(array $array, int $identation = 0) use (&$write_array, $array_reduce_key) : string | |
| { | |
| $spaces_to_organize = fn(int $identation_number) : string => str_repeat(' ', $identation_number*4); | |
| $result = $array_reduce_key($array, function($carry, $key, $value) | |
| use ($write_array, $identation, $spaces_to_organize ) | |
| { | |
| $boolean_to_string = fn(bool $maybe_boolean): string => $maybe_boolean ? 'true' : 'false'; | |
| $return_data_type = fn($data_type): string => | |
| (is_string($data_type) | |
| ? "'$data_type'" | |
| : ((is_bool($data_type)) ? $boolean_to_string($data_type) : "$data_type")); | |
| $array_element = (fn():string =>(!is_array($value)) | |
| ? $return_data_type($key)." => ".$return_data_type($value) | |
| /* Este + 2 al parecer funciona, y no entiendo por que. */ | |
| : "'$key' => ".PHP_EOL.$write_array($value, $identation + 2))(); | |
| return $carry.$spaces_to_organize($identation+1).$array_element.','.PHP_EOL; | |
| }, ''); | |
| return $spaces_to_organize($identation).'['.PHP_EOL.$result.$spaces_to_organize($identation).']'; | |
| }; | |
| print($write_array($array_aplanar)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment