【问题标题】:Mapping undefined json properties映射未定义的 json 属性
【发布时间】:2017-10-10 22:30:58
【问题描述】:

谁能建议我一个以干净的方式将 json 解码对象映射到 pdo 语句的好习惯?

我为从不同客户端应用程序请求的 crud 操作创建了一个 api(使用 slimslim-pdo)。 有些表很大,有几个可以为空的列。 这意味着在大多数情况下,发布的 json 不会包含所有列数据。

示例:

    $item= json_decode($req->getBody());
    $insertStatement = $pdo->insert(array('prop1', 'prop2', 'prop3',..., 'prop10'))
                           ->into('table')
                           ->values(array($item->prop1, $item->prop2, $item->prop3,..., 'server side value 10') ));

当从客户发布类似这样的内容时......

{"prop" : "foo" , "prop2" : "bar"}

...php 记录如下警告:

PHP 注意:未定义的属性:stdClass::$prop3 in /home/... 上线...

因为 prop3 在 json 中不存在。

我知道这可以通过使用 php property_exists() 和/或 isset() 来避免。 但是,对几十个操作代码的所有语句中的所有属性都这样做会变得庞大而混乱。

我已经用谷歌搜索了一个干净的解决方案。 最初通过搜索未定义属性的方式充当null。 然后寻找对象映射方法。

有什么建议吗?

非常感谢! :)

【问题讨论】:

  • 如果使用 PHP 7,您可以使用 Null Coalesce 运算符 ??,因此 $item->prop3??null 将在不存在时将值设置为 null。

标签: php json slim


【解决方案1】:

我会这样做

$json = '{"prob": "foo", "prop2": "bar"}';
$jsonArray = json_decode($json, true);// this will decode json in array
// $jsonArray will be: ["prop" => "foo", "prop2" => "bar"]
// array_keys will be: ["prop", "prop2"]
// array_values wil be: ["foo", "bar"];

$insertStatement = $pdo->insert(array_keys($jsonArray))
                           ->into('table')
                           ->values(array_values($jsonArray));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 2021-08-12
    • 2018-01-07
    • 1970-01-01
    相关资源
    最近更新 更多