[英]Count specific elements of an array in php
我想計算數組的特定元素(“ host_name”)。
我的功能是解碼json文件並返回數組。
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"
}
]
}
我的php頁面解碼json文件:
的functions.php
function test($clusterName)
{
$content = file_get_contents($clusterName.".json");
$content = utf8_encode($content);
$result = json_decode($content, true);
return $result;
}
我想在其中顯示主機名數量的頁面:
page.php文件
$result = test("mycluster");
echo "<p>".count($result['Hosts']['host_name'])."</p>";
但是當我這樣做時,我對“主機”有一個未定義的索引。 我嘗試了一些事情,我可以說數組就在那里(print_r顯示了它),但是我真的無法計算它的元素。
謝謝
您必須計算“項目”的要素。
echo "<p>".count($result['items'])."</p>";
你可以用
$c = count($result['items']) ;
您可以遍歷項目和主機,並檢查host_name是否存在。
$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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.