I have a set of JSON rules that I am attempting to convert to a PHP array.
This is the set of rules:
{
"rules" : {
"full_name" : "required",
"email" : {
"required" : true,
"email" : true
},
"phone" : {
"required" : true,
"maxlength" : 10
},
"comments" : {
"minlength" : 10
}
}
}
This is the final output I am working towards:
$rules = [
'full_name' => 'required',
'email' => [ 'required', 'email'],
'phone' => [ 'max_length' => 10 ],
'message' => [ 'min_length' => 10 ]
];
I've created this translation method that reads the json data after json_decode:
private function convertRules($rules)
{
$convertedRules = [];
foreach( $rules as $key => $value ) {
if( is_array($value)) {
$value = $this->convertRules($value);
}
switch( $key ) {
case '1':
$value = $key;
break;
case 'minlength':
$key = 'min_length';
break;
case 'maxlength':
$key = 'max_length';
break;
}
switch( $value ) {
case '1':
$value = $key;
break;
}
$convertedRules[$key] = $value;
}
return $convertedRules;
}
But it creates an array with keys that duplicate the values.
Array
(
[full_name] => required
[email] => Array
(
[required] => required
[email] => email
)
[phone] => Array
(
[required] => required
[max_length] => 10
)
[comments] => Array
(
[min_length] => 10
)
)
How can I get an array without keys similar to the PHP rules array above?
Any PHP7 optimizations are also appreciated!
phonekey supposed to be'phone' => [ 'required', 'max_length' => 10 ]?