【问题标题】:How to input JSON data with dynamic data array?如何使用动态数据数组输入 JSON 数据?
【发布时间】:2016-09-29 20:51:20
【问题描述】:

第 1 个人输入数据,数据数组如下所示:

{
  "type": "1",
  "name": "John", 
  "phone":"898171"
}

人 2 没有设置电话,数据数组如下所示:

{
  "type": "1",
  "name": "Lisa"
}   // only write 2 array...

我的控制器中有这样的源代码:

$data = json_decode(file_get_contents('php://input'), true);

if(!$data['phone']->iSEmpty){
   echo "you haven't set the phone number!"
}

但这不起作用。第 2 个人输入数据时出现以下错误 -

“未定义索引:电话”

【问题讨论】:

    标签: php arrays json laravel


    【解决方案1】:

    问题是您正在尝试检查未定义键的值。

    您可以使用 array_key_exists 来检查它:

    if (!array_key_exists('phone', $data)) {
        echo "you haven't set the phone number!";
    }
    

    【讨论】:

    • 在阅读您的评论之前,我尝试像这样 array_key_exists($data['phone']); ...哈哈..谢谢..您的解决方案有效!!!
    • 我很高兴知道我可以帮助你! :)
    • 如果它工作正常,你能接受正确答案吗?谢谢!
    【解决方案2】:

    试试

    if(!isset($data['phone'])){ echo "you haven't set the phone number!" }
    

    【讨论】:

    • 为什么 OP 应该“尝试”这个? 好的答案将始终解释所做的事情以及为什么以这种方式完成,不仅是为了 OP,也是为了 SO 的未来访问者。跨度>
    • 一个人可以尝试很多东西...我没有时间尝试。您在发布之前尝试过吗?
    • 感谢您的反馈。下次我会解释的。
    猜你喜欢
    • 1970-01-01
    • 2019-01-24
    • 2022-10-04
    • 2020-09-13
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    相关资源
    最近更新 更多