检查 POST 数据 - JSON 数组

Check POST Data - JSON Array

我正在尝试检查我的 JSON 文件的数据。它适用于 json 文件中的字符串,但是如何处理数组中的数组?

我发送的内容:

{
    "info" : "test",
    "data" : [
        { 
            "startdate": "2018-01-01T10:00:00+0100",
            "enddate": "2018-01-01T17:00:00+0100"
        }
     ]
}

我还有什么:

$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!');     
    }
}

但是函数 empty 到目前为止对数组有效。它会 return false,因为数组在那里。我如何检查 "startdate" 键?

顺便说一句:我正在使用 symfony3(FOSRestBundle),php 7.0

您可以检查该值是否为数组并从中过滤空值,然后测试它是否为空。

$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() 函数的默认行为是从数组中删除所有等于 null0''false 的值(如果没有传递回调) .

注意:我假设您想要检索 data 而不是 date

by LBA, I also suggest to check the Symfony Validation component 改为处理该问题。