I am working with api with laravel/php and I need the data in following format. It would be great if you can help me or give some hint.
if I do dd() $formData which is submitted from the form I get following array
dd($formData);
dd($formData) gives below result
array:3 [▼
"fname" => "john"
"lname" => "doe"
"age" => "22"
]
Now, Since the $formData
array length is 3, I need three array and their key
should be assigned to field_name
,value
should be assigned to value
and based on value it should be either text
, number
or date
. Number if value is numeric
, date if value is in format 2010-12-01 or 2010/12/01.dd/mm/yyyy otherwise it will be text
Now I need an array that return data in below format. $formData to $newFormData and $newFormData should have following data
output:
[
'field_name' => 'fname',
'value_type' => 'text', //should be text if value is not number or date format
'value' => 'john',
],
[
'field_name' => 'lname',
'value_type' => 'text',//should be text if value is not number or date
'value' => 'doe',
],
[
'field_name' => 'age',
'value_type' => 'number',//should be number if value is numeric
'value' => '22',
]
CodePudding user response:
I would recommend to use laravel collections for this use case with the map method.
$formData = [
"fname" => "john",
"lname" => "doe",
"age" => "22",
"date" => "2010-12-01",
];
$result = collect($formData)->map(function ($value, $key) {
return [
'field_name' => $key,
'value' => $value,
'value_type' => getValueType($value),
];
})->values();
and here the getValueType
function:
function getValueType($value)
{
if (is_numeric($value)) return 'number';
$isDate = true;
try {
Carbon\Carbon::parse($value);
} catch (\Throwable $th) {
$isDate = false;
}
if ($isDate) return 'date';
return 'text';
}
If you would like to have a plain PHP array in the $result
variable, then you can add ->toArray()
after ->values()
.
CodePudding user response:
Initialize the result as empty array
$result = [];
Loop through the form data
foreach($formData as $key => $data){
$tempData['field_name'] = $key;
$tempData['value_type'] = retrieveValueType($data);
$tempData['value'] = $data;
$result[] = $tempData; //Append array to object
}
Creating a function to retrieve the value type
function retrieveValueType($value){
if(is_numeric($value)){
return 'numeric';
}else{
$isDateValid = DateTime::createFromFormat('d-m-Y', $value);
if($isDateValid){
return 'date';
}
return 'text';
}
}
It will provide the result as you require
^ array:3 [▼
0 => array:3 [▼
"field_name" => "fname"
"value_type" => "text"
"value" => "john"
]
1 => array:3 [▼
"field_name" => "lname"
"value_type" => "text"
"value" => "doe"
]
2 => array:3 [▼
"field_name" => "age"
"value_type" => "number"
"value" => "22"
]
]