【问题标题】:How to add object inside object in php?如何在php中的对象内添加对象?
【发布时间】:2017-04-23 16:19:06
【问题描述】:

我目前在创建 json 响应时遇到问题,因为我使用的 PHP 不多,但任何人都可以帮我创建如下所示的 json:

{
  "set_attributes": 
    {
      "apikey": "some value",
    },
  "block_names": ["getdata"],
  "type": "show_block",
  "title": "go"
}

这是我的代码:

    $response = array();
    $response['block_names'] = array();
    $response['block_names'] = "getdata";
    $response['type'] = "show_block";
    $response['title'] = "go";

    if ($db->studentLogin($username, $password)) {
        $student = $db->getStudent($username);
        $temp = array();
        $temp['apikey'] = $student['api_key'];
        $response['set_attributes'] = $temp['apikey'];
    } else {
        $temp = array();
        $response['messages'] = array();
        $temp['text'] = "Invalid username or password";
        array_push($response['messages'],$temp);
    }
    echoResponse(200, $response);

显示如下:

{
  "block_names": "getdata",
  "type": "show_block",
  "title": "go",
  "set_attributes": "f74911b29778adea86aa24d5ce85ff58"
}

但我想在 set_attributes 内添加 apikey = "f74911b29778adea86aa24d5ce85ff58" 和在 block_names 外添加 [] 就像上面一样。我该怎么做?

【问题讨论】:

  • $response['set_attributes'] = $temp; - 现在你只取值
  • $response['block_names'] = array("getdata");

标签: php json


【解决方案1】:

试试这个:

$response['block_names'] = array("getdata");
...
$response['set_attributes'] = new \stdClass();
$response['set_attributes']->apikey = 'some_api_key';

https://3v4l.org/GDMKT#output

【讨论】:

    猜你喜欢
    • 2018-07-16
    • 2021-12-30
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多