Reputation: 510
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
Upvotes: 0
Views: 53
Reputation: 1579
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
Upvotes: 1
Reputation: 2229
You have to count the elemets of "items".
echo "<p>".count($result['items'])."</p>";
Upvotes: 1