0

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

1
  • What did you try so far? What is the problem to count? Commented Jul 28, 2017 at 17:55

3 Answers 3

1

You have to count the elemets of "items".

echo "<p>".count($result['items'])."</p>";
Sign up to request clarification or add additional context in comments.

1 Comment

Same answer : Undefined index: items
1

You could use

$c = count($result['items']) ;

2 Comments

Can we see a print_r of $result as returned by test()?
Ok my bad, it works now. I changed the code in the meantime and I was returning $result['items'] in my function instead of $result. So it's good now, thanks!
1

You can loop through the items and hosts and check if host_name is present.

$result = test("mycluster");

$count = 0;
foreach($result['items'] as $item) {
    $count += isset($item['Hosts']) && isset($item['Hosts']['host_name']) ? 1 : 0;
}
print_r($count); // will print 3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.