I´m trying to check the data of my JSON file. It works for strings in the json file, but how to handle it with arrays in the array?
What i send:
{
"info" : "test",
"data" : [
{
"startdate": "2018-01-01T10:00:00+0100",
"enddate": "2018-01-01T17:00:00+0100"
}
]
}
What i´ve yet:
$dataReq = array(
'info' => $request->get('info'),
'date' => $request->get('date'), // my array
);
foreach ($dataReq as $a => $value) {
if(empty($value)) {
return new View('The field \''.$a.'\' is required!');
}
}
But the function empty
doenst work for arrays so far. It will return false, cause the array is there. How can i check the "startdate" key?
btw: i´m using symfony3(FOSRestBundle), php 7.0
You can check if the value is an array and filter null values from it, then test if it's empty.
$dataReq = array(
'info' => $request->get('info'),
'data' => $request->get('data'), // my array
);
foreach ($dataReq as $a => $value) {
if(is_array($value)) $value = array_filter($value);
if(empty($value)) {
return new View('The field \''.$a.'\' is required!');
}
}
array_filter()
function's default behavior is to remove from array all values equal to null
, 0
, ''
or false
if no callback is passed.
Note: I assume you wanted to retrieve data
and not date
.
As commented by LBA, I also suggest to check the Symfony Validation component to deal with that instead.