-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Alaa Sarhan
committed
Sep 27, 2016
1 parent
b6cbd0a
commit 995f977
Showing
1 changed file
with
85 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
# php-flatten | ||
|
||
A utility function to mainly flatten multidimensional-arrays and traversables into a one-dimensional array, preserving keys | ||
and joining them with a customizable separator to from fully-qualified keys in the final array. | ||
|
||
## Installation | ||
|
||
``` | ||
composer require sarhan/php-flatten | ||
``` | ||
|
||
## Examples | ||
|
||
```php | ||
use Sarhan\Flatten; | ||
|
||
$multiArray = [ | ||
'say' => 'what', | ||
'hi' => [ 'de' => 'Hallo', 'es' => 'Hola' ] | ||
]; | ||
|
||
$array = Flatten::flatten($multiArray); | ||
|
||
/* print_r($array) gives: | ||
|
||
Array | ||
( | ||
[say] => what | ||
[hi.de] => Hallo | ||
[hi.es] => Hola | ||
) | ||
*/ | ||
``` | ||
|
||
Custom Separator and initial prefix | ||
```php | ||
use Sarhan\Flatten; | ||
|
||
$allowAccess = [ | ||
'root' => false, | ||
'var' => [ 'log' => ['nginx' => true, 'apt' => false], 'www' => true ], | ||
]; | ||
|
||
$allowAccess = Flatten::flatten($allowAccess, '/', '/'); | ||
|
||
/* var_dump($array) gives: | ||
|
||
array(4) { | ||
'/root' => | ||
bool(false) | ||
'/var/log/nginx' => | ||
bool(true) | ||
'/var/log/apt' => | ||
bool(false) | ||
'/var/www' => | ||
bool(true) | ||
} | ||
*/ | ||
``` | ||
|
||
Notice that the prefix will not be separated in FQkeys. If it should be separated, separator must be appeneded to the prefix string. | ||
```php | ||
use Sarhan\Flatten; | ||
|
||
$api = [ | ||
'category' => [ 'health' => 321, 'sport' => 769, 'fashion' => 888 ], | ||
'tag' => [ 'soccer' => 7124, 'tennis' => [ 'singles' => 9833, 'doubles' => 27127 ] ], | ||
]; | ||
|
||
$uris = Flatten::flatten($api, '/', 'https://api.dummyhost.domain/'); | ||
|
||
/* print_r($uris) gives: | ||
|
||
Array | ||
( | ||
[https://api.dummyhost.domain/category/health] => 321 | ||
[https://api.dummyhost.domain/category/sport] => 769 | ||
[https://api.dummyhost.domain/category/fashion] => 888 | ||
[https://api.dummyhost.domain/tag/soccer] => 7124 | ||
[https://api.dummyhost.domain/tag/tennis/singles] => 9833 | ||
[https://api.dummyhost.domain/tag/tennis/doubles] => 27127 | ||
) | ||
|
||
*/ | ||
``` |