dongyuling0312 2017-07-28 17:52
浏览 44
已采纳

在php中计算数组的特定元素

I would like to count specific elements ('host_name') of an array.

My function is decoding a json file and returning the array.

file.json

{
    "href": "https://webservice:8080",
    "items": [
        {
            "Hosts": {
                "cluster_name": "cluster1",
                "host_name": "server1"
            },
            "href": "https://server1:8080"
        },
        {
            "Hosts": {
                "cluster_name": "cluster1",
                "host_name": "server2"
            },
            "href": "https://server2:8080"
        },
        {
            "Hosts": {
                "cluster_name": "cluster1",
                "host_name": "server3"
            },
            "href": "https://server3:8080"
        }
    ]
}

My php page to decode the json file :

functions.php

function test($clusterName)
{
$content = file_get_contents($clusterName.".json");
                $content = utf8_encode($content);
                $result = json_decode($content, true);

                return  $result;
}

And my page where i'd like to display the number of host names :

page.php

$result = test("mycluster");
echo "<p>".count($result['Hosts']['host_name'])."</p>";

But I have an undefined index for 'Hosts' when I do this. I tried some things, I can tell that the array is well there (print_r shows it), but I really can't count elements of it.

Thanks

  • 写回答

3条回答 默认 最新

  • dongruidian3064 2017-07-28 17:57
    关注

    You have to count the elemets of "items".

    echo "<p>".count($result['items'])."</p>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题