transform array keys easily.
Via Composer
$ composer require shetabit/transformer
you can transform array keys using get($transformer)
method
$originalData = [
'f_name' => 'mahdi',
'l_name' => 'khanzadi'
];
$role = [
'f_name' => 'first_name',
'l_name' => 'last_name',
];
$transformer = new Transformer($role);
$transformedData = (new Transform($originalData))->get($transformer);
/*
data:
[
'first_name' => 'mahdi',
'last_name' => 'khanzadi'
]
*/
or you can use from($currentFormat)
and to($destinationFormat)
.
$originalData = [
'f_name' => 'mahdi',
'l_name' => 'khanzadi'
];
$transformer = new Transformer();
// convert f_name to first_name
$transformer->from('f_name')->to('first_name');
// convert l_name to last_name
$transformer->from('l_name')->to('last_name');
$transformedData = (new Transform($originalData))->use($transformer)->get();
/*
data:
[
'first_name' => 'mahdi',
'last_name' => 'khanzadi'
]
*/
as you see, you can set original data dynamically using setOriginalData
method.
you can use Shetabit\Transform\Classes\Transformer
to transform array keys.
if you have complex array structures, you can create a custom transformer by implementing TransformerInterface
// at the top
use Shetabit\Transformer\Contracts\TransformerInterface;
// ...
class CustomTranformerName implements TransformerInterface
{
/**
* Transform data
*
* @return array
*/
public function transform(array $data) : array
{
return [
'user_name' => $data['u'],
'password' => $data['p']
];
}
}
// use your custom transformer
$originalData = [
'u' => 'mahdikhanzadi',
'p' => '246810'
];
$transformer = new CustomTranformerName();
$transformedData = (new Transform($originalData))->get($transformer);
/*
data:
[
'username' => 'mahdikhanzadi',
'password' => '246810'
]
*/
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING and CONDUCT for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.