dongleman4760 2012-08-27 08:50
浏览 21
已采纳

如何制作具有相同名称的PHP stdClass对象?

I'm working against an API that gives me an stdClass object that looks like this (actual data replaced)

"data": [
    {
      "type": "image",
      "comments": {
        "data": [
          {
            "created_time": "1346054211",
            "text": "Omg haha that's a lot of squats",
            "from": {},
            "id": "267044541287419185"
          },
          {
            "created_time": "1346054328",
            "text": "Fit body",
            "from": {},
            "id": "267045517536841021"
          },
        ]
      },
      "created_time": "1346049912",
    },

How is it possible to create an stdClass object like "Comments" that have multiple sub fields all with same name but different data. When I try to create an stdClass looking like this my Comments section will only contain 1 input which is the final one in the while loop. So instead of applying to the bottom it's replacing the old data with the new one. How to fix this?

  • 写回答

1条回答 默认 最新

  • dou12754 2012-08-27 08:58
    关注

    "comments" is an object with a key "data" which is an array of objects. You cannot reuse the same key in any language, JSON, PHP, stdClass or otherwise. You want to make an array of similar objects.

    $comments = new stdClass;
    $comments->data = array();
    
    for ($i = 0; $i < 2; $i++) {
        $comment = new stdClass;
        $comment->text = 'Lorem ipsum...';
        ...
        $comments->data[] = $comment;
    }
    
    var_dump($comments);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?