PHP中的JSON对象插入

时间:2017-12-22 10:51:35

标签: php arrays json object

我在以正确的方式在JSON对象中插入一些数据时遇到了一些问题。我希望JSON对象在对象之上没有任何键。这样说明就是我的JSON:

JSON NOW:

{
    "Account2": [{
        "accountId": "",
        "containerId": "",
        "tag": 1,
        "trigger": 1,
        "variable": 4,
        "account_name": "Account2"
    }, {
        "accountId": "",
        "containerId": "",
        "missing_live": true
    }],
    "Account 1": [{
        "accountId": "",
        "containerId": "",
        "tag": 2,
        "trigger": 1,
        "variable": 1,
        "account_name": "Account 1"
    }],
    "GTMdocx": [{
        "accountId": "",
        "containerId": "",
        "tag": 0,
        "trigger": 0,
        "variable": 1,
        "account_name": "GTMdocx"
    }]
}

正如您可以看到“Account2”,“帐户1”,“GTMdocx”等...它们就像json对象中的account_name。我想删除“顶部”-key并保留“account_name”。但是当我删除代码中的行时,我只得到一个响应(一个JSON对象)而不是全部3个。

PHP代码:

       try { // Some containers might not have live-version
            $container_version = self::listAccountsContainersVersion($account_container['path']);
            $account_container->tag = count($container_version['tag']);
            $account_container->trigger = count($container_version['trigger']);
            $account_container->variable = count($container_version['variable']);
            $account_container->account_name = $account['name'];

            // Add the whole account to the main container
            $containers[$account['name']][] = $account_container;

        } catch (\Exception $e) {
            $account_container->missing_live = true;
            $containers[$account['name']][] = $account_container;

            //$containers[$account['name']]['missing_live_version'] = $account_container; //Container not published
        }

我评论//将整个帐户添加到主容器中...这里是所有错误的行。我试图将其改为:

$containers[$account] = $account_container;

所以我将获得$account中包含的所有$account_container JSON对象,但如果我没有$account['name'],则响应在其3时只显示一个对象。(这是在foreach loop)。

所以我希望一个JSON对象看起来像这样:

{
    "1": {
        "accountId": "",
        "containerId": "",
        "tag": 1,
        "trigger": 1,
        "variable": 4,
        "account_name": "Account2"
    },
    "2": {
        "accountId": "",
        "containerId": "",
        "missing_live": true,
        "account_name": "Account2"
    },
    "3": {
        "accountId": "",
        "containerId": "",
        "tag": 2,
        "trigger": 1,
        "variable": 1,
        "account_name": "Account 1"
    },
    "4": {
        "accountId": "",
        "containerId": "",
        "tag": 0,
        "trigger": 0,
        "variable": 1,
        "account_name": "GTMdocx"
    },
    "5": {
        "accountId": "",
        "containerId": "",
        "tag": 0,
        "trigger": 0,
        "variable": 0,
        "account_name": "Account3"
    }
}

你可以看到我删除了顶部的“Account2”。

1 个答案:

答案 0 :(得分:1)

因此,要获得所需的JSON字符串,您需要具有单个维度数组

所以请保存 account_container ,就像这样

$containers[] = $account_container;