pflorek / elevator
Flattens a multi-dimensional array or any \Traversable into a one-dimensional array. Elevates an one-dimensional or any \Traversable to a multi-dimensional array.
Installs: 12 754
Dependents: 1
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: >=5.4
- symfony/polyfill-php71: ^1
Requires (Dev)
- phpunit/phpunit: >=4.8.36 <8.0
README
This library provides a simple way to elevate a map (associative array) to a tree or to flatten a tree to a map (associative array). The tree's node keys are the tokens of the map's materialized path separated by a delimiter.
This library comes handy to map flat lists like SQL results to
documents. The result's column name could be a materialized path of
the target document. You can pass a result row to Elevator::up
and
proceed marshalling by passing the elevated tree to a JSON or XML
serializer. On unmarshalling just pass the deserialized array tree
to Elevator::down
and feed e.g. a SQL statement.
Usage
Elevate
Elevate a map with materialized paths to a tree:
use PFlorek\Elevator\Elevator; use PFlorek\Elevator\ElevatorFactory; use function \PFlorek\Elevator\array_elevate; $flattened = [ 'World.Asia.Afghanistan.0' => '...', 'World.Africa' => true, 'World.Antarctica' => -25.2, 'World.Europe' => new \stdClass(), 'World.North America' => [], ]; // object oriented $factory = ElevatorFactory::getInstance(); $elevator = $factory->create(); $elevator->up($flattened); // or functional $elevated = array_elevate($flattened); var_dump($elevated); //returns ["World"] => array(5) { // ["Asia"] => array(1) { // ["Afghanistan"] => array(1) { // [0] => string(3) "..." // } // } // ["Africa"] => bool(true) // ["Antarctica"] => float(-25.2) // ["Europe"]=> object(stdClass)#298 (0) {} // ["North America"]=> [] //}
Flatten
Flattens a tree to a map which keys are the materialized path of the node's keys:
use PFlorek\Elevator\Elevator; use PFlorek\Elevator\ElevatorFactory; use function \PFlorek\Elevator\array_flatten; $elevated = [ 'World' => [ 'Asia' => [ 'Afghanistan' => [ '...' ] ], 'Africa' => true, 'Antarctica' => -25.2, 'Europe' => new \stdClass(), 'North America' => [], ] ]; // object oriented $factory = ElevatorFactory::getInstance(); $elevator = $factory->create(); $elevator->down($flattened); // or functional $flattened = array_flatten($elevated); var_dump($flattened); //returns array(5) { // ["World.Asia.Afghanistan.0"] => string(3) "..." // ["World.Africa"] => bool(true) // ["World.Antarctica"] => float(-25.2) // ["World.Europe"] => object(stdClass) (0) { } // ["World.North America"] => array(0) { } //}
Installation
Use Composer to install the package:
composer require pflorek/elevator
Authors
Contribute
Contributions are always welcome!
- Report any bugs or issues on the issue tracker.
- You can download the sources at the package's Git repository.
License
All contents of this package are licensed under the MIT license.