|
| 1 | +# php-flatten |
| 2 | + |
| 3 | +A utility function to mainly flatten multidimensional-arrays and traversables into a one-dimensional array, preserving keys |
| 4 | +and joining them with a customizable separator to from fully-qualified keys in the final array. |
| 5 | + |
| 6 | +## Installation |
| 7 | + |
| 8 | +``` |
| 9 | + composer require sarhan/php-flatten |
| 10 | +``` |
| 11 | + |
| 12 | +## Examples |
| 13 | + |
| 14 | +```php |
| 15 | +use Sarhan\Flatten; |
| 16 | + |
| 17 | +$multiArray = [ |
| 18 | + 'say' => 'what', |
| 19 | + 'hi' => [ 'de' => 'Hallo', 'es' => 'Hola' ] |
| 20 | +]; |
| 21 | + |
| 22 | +$array = Flatten::flatten($multiArray); |
| 23 | + |
| 24 | +/* print_r($array) gives: |
| 25 | + |
| 26 | + Array |
| 27 | + ( |
| 28 | + [say] => what |
| 29 | + [hi.de] => Hallo |
| 30 | + [hi.es] => Hola |
| 31 | + ) |
| 32 | +*/ |
| 33 | +``` |
| 34 | + |
| 35 | +Custom Separator and initial prefix |
| 36 | +```php |
| 37 | +use Sarhan\Flatten; |
| 38 | + |
| 39 | +$allowAccess = [ |
| 40 | + 'root' => false, |
| 41 | + 'var' => [ 'log' => ['nginx' => true, 'apt' => false], 'www' => true ], |
| 42 | +]; |
| 43 | + |
| 44 | +$allowAccess = Flatten::flatten($allowAccess, '/', '/'); |
| 45 | + |
| 46 | +/* var_dump($array) gives: |
| 47 | + |
| 48 | + array(4) { |
| 49 | + '/root' => |
| 50 | + bool(false) |
| 51 | + '/var/log/nginx' => |
| 52 | + bool(true) |
| 53 | + '/var/log/apt' => |
| 54 | + bool(false) |
| 55 | + '/var/www' => |
| 56 | + bool(true) |
| 57 | + } |
| 58 | +*/ |
| 59 | +``` |
| 60 | + |
| 61 | +Notice that the prefix will not be separated in FQkeys. If it should be separated, separator must be appeneded to the prefix string. |
| 62 | +```php |
| 63 | +use Sarhan\Flatten; |
| 64 | + |
| 65 | +$api = [ |
| 66 | + 'category' => [ 'health' => 321, 'sport' => 769, 'fashion' => 888 ], |
| 67 | + 'tag' => [ 'soccer' => 7124, 'tennis' => [ 'singles' => 9833, 'doubles' => 27127 ] ], |
| 68 | +]; |
| 69 | + |
| 70 | +$uris = Flatten::flatten($api, '/', 'https://api.dummyhost.domain/'); |
| 71 | + |
| 72 | +/* print_r($uris) gives: |
| 73 | + |
| 74 | + Array |
| 75 | + ( |
| 76 | + [https://api.dummyhost.domain/category/health] => 321 |
| 77 | + [https://api.dummyhost.domain/category/sport] => 769 |
| 78 | + [https://api.dummyhost.domain/category/fashion] => 888 |
| 79 | + [https://api.dummyhost.domain/tag/soccer] => 7124 |
| 80 | + [https://api.dummyhost.domain/tag/tennis/singles] => 9833 |
| 81 | + [https://api.dummyhost.domain/tag/tennis/doubles] => 27127 |
| 82 | + ) |
| 83 | + |
| 84 | +*/ |
| 85 | +``` |
0 commit comments