在php

时间:2017-07-28 17:52:56

标签: php arrays json

我想计算一个数组的特定元素(' 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>";

但我有一个未定义的索引,用于&#39;主机&#39;当我这样做。我尝试了一些东西,我可以说阵列很好(print_r显示它),但我真的无法计算它的元素。

由于

3 个答案:

答案 0 :(得分:1)

你必须计算“项目”的元素。

echo "<p>".count($result['items'])."</p>";

答案 1 :(得分:1)

您可以使用

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

答案 2 :(得分:1)

您可以遍历项目和主机,并检查host_name是否存在。

string result;
using (var db = Dal.MyEntities(false))
{
    result = db.TableA
                .Select(c => new { SupplierId = c.SupplierID, SupplierName = c.SupplierName })
                .Union(db.TableB.Select(g => new { (int?)g.SupplierId, SupplierName = g.Name }))
                .Where(c => c.SupplierId == supplierId)
                .Select(c => c.SupplierName)
                .FirstOrDefault();
}
相关问题