【问题标题】:PHP count() always return 1 [duplicate]PHP count() 总是返回 1 [重复]
【发布时间】:2018-05-13 04:10:31
【问题描述】:

我有一个 JSON 对象,我试图迭代以计算对象内部有多少值。

我的 JSON;

[{
    "accountId": "1746756959",
    "containerId": "7454209",
    "containerVersionId": "7",
    "container": {
        "accountId": "1746756959",
        "containerId": "7454209"
    },
    "tag": [{
        "accountId": "1746756959",
        "name": "Universal Analytics",
        "parameter": [{
            "key": "overrideGaSettings",
            "type": "boolean",
            "value": "false"
        }]
    }, {
        "accountId": "1746756959",
        "parameter": [{
            "key": "detectTitle",
            "type": "boolean",
            "value": "true"
        }]
    }, {
        "accountId": "1746756959",
        "name": "contentEngagement",
        "parameter": [{
            "key": "html",
            "type": "template",
            "value": "<script>\n\n<\/script>"
        }]
    }],
    "trigger": [{
        "accountId": "1746756959",
        "name": "Trigger 1",
        "workspaceId": null
    }, {
        "accountId": "1746756959",
        "name": "Trigger 2",
        "workspaceId": null
    }, {
        "accountId": "1746756959",
        "containerId": "7454209",
        "fingerprint": "1507893475158",
        "name": "Trigger 3",
        "notes": null,
        "parentFolderId": null,
        "path": null,
        "tagManagerUrl": null,
        "triggerId": "13",
        "type": "windowLoaded",
        "workspaceId": null
    }],
    "variable": [{
        "accountId": "1746756959",
        "containerId": "7454209",
        "disablingTriggerId": null,
        "enablingTriggerId": null,
        "fingerprint": "1505216399119",
        "name": "Google Analytics Settings",
        "notes": null,
        "parentFolderId": null,
        "path": null,
        "scheduleEndMs": null,
        "scheduleStartMs": null,
        "tagManagerUrl": null,
        "type": "gas",
        "variableId": "1",
        "workspaceId": null,
        "parameter": [{
            "key": "cookieDomain",
            "type": "template",
            "value": "auto"
        }]

    }]
}]

当我尝试迭代并打印出我可以做到的值时,但是当我计算它时,我得到的结果类似于(1 1 1),而应该是(3)。我怀疑这与foreach有关。我的 PHP 代码如下所示:

   foreach($LiveContainer as $item) {
            foreach ($item['tag'] as $accountPath) {
                echo count($accountPath->name); echo "<br>";
            }}

结果:

1 1 1

我想要计算tag中有多少项目。

PS:我从 JSON 中删除了很多,因为它很长,可能并非所有标签都提供“名称”,对此感到抱歉

谢谢

【问题讨论】:

  • count($item['tag']) 有什么问题?

标签: php json loops foreach


【解决方案1】:
foreach($LiveContainer as $item) {
    echo count($item['tag']); echo "<br>";
}

【讨论】:

  • 愚蠢愚蠢的我,我忘了回应它,这就是为什么它第一次不起作用所以我做了两个 foreach。很抱歉浪费您的时间,非常感谢
  • 管理员可以删除这篇文章。只是浪费服务器上的空间:P
  • @Asim 你可以自己删除,看问题末尾的删除链接(连同分享、编辑...)
  • 不可能。说人们已经在这里使用了很多时间,这就是为什么我不能删除它
猜你喜欢
  • 2011-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-05
  • 2011-12-16
  • 1970-01-01
相关资源
最近更新 更多