Download the PHP package salamanderbe/array-mapper without Composer
On this page you can find all versions of the php package salamanderbe/array-mapper. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download salamanderbe/array-mapper
More information about salamanderbe/array-mapper
Files in salamanderbe/array-mapper
Package array-mapper
Short Description Simple mapper to map an object to an array based on a configuration
License MIT
Informations about the package array-mapper
An easy and simple way to map objects to arrays
Installation
Examples
Basic example
Given a simple object with the following values (JSON):
When we pass this as an object (e.g. json_decode) to the map function with the following mapping configuration:
The function will map the source oject's identifier field to the output's id field, the same goes for title and name. resulting in the following array:
Fixed values
Starting with the following source object:
With the #
notation we can easily add a fixed value not present on the source object:
Now we have an array containing our fixed value:
note: if your source field contains a #
character you can escape it by adding another #
character e.g. ##type
Nesting
Using the same object as above:
We can easily create nested mappings using the a config like the following:
This will result in the following array:
Nested object fields on the source object
When your source object has a child object:
You can use the .
notation to access child fields, like the following example config:
The child's _childtitle field will now be mapped to output's _childname field resulting in the following output:
Arrays on the source object
Given the following object:
When we want to map fields contained in child objects we can use the *
notation to indicate we want a field from an array of objects, for example:
Now the _childnames field on the output array will contain all the child's _childtitle fields:
Arrays in the result array
Say you want to map the children into a nested array:
We can use the .*
notation on the output field to indicate we want to map multiple children's fields
Now all the source objects' children _childtitle fields will be mapped to a children array on the output array, each item inside children will be an array with the child's title field mapped to the output's name field:
Merging arrays in the result array
Let's assume we have a source object with 2 array which we want to be combined in a single result:
We can combine these using the same syntax as with the arrays but instead nesting multiple sources:
This will result in a result array with a descendants field containing both the source's children and grandchildren: