来自json获得特定项目的多维数组

时间:2015-08-06 23:25:49

标签: php json multidimensional-array

我已经在这方面工作了很长时间,而且我无法找到解决方案,任何帮助都会得到满足

这是我的JSON文件:

{   "city": "Drf",
    "tels": {
    "1": {
        "name": "Hilorf",
        "adr": "eldo",
        "partners": {
            "101": {
                "name": "xyz.com",
                 "prices": {
                    "1001": {
                        "description": "Single Room",
                        "amount": 125
                    },
                    "1002": {
                        "description": "Double Room",
                        "amount": 139
                    }
                }
            }
        }
    },
    "2": {
        "name": "Mer",
        "adr": "lichef",
        "partners": {
            "201": {
                "name": "vg.com",
                "prices": {
                    "2001": {
                        "description": "Single Room",
                        "amount": 52
                    },
                    "2002": {
                        "description": "Double Room",
                        "amount": 52
                    }
                }
            }
        }
    }
}

}

这是我的php文件

 <?php
$json_file = file_get_contents('xyz.json');
$jfo = json_decode($json_file, TRUE);
foreach("tried a lot here nothing seems to work fo me")

这里我想获取一个数组中的所有金额值。我无法得到它请帮助我。

1 个答案:

答案 0 :(得分:0)

您需要多个foreach()语句来执行此操作,每个级别一个。

$amounts = [];
foreach ($jfo as $people) {
    foreach ($people as $person) {
        foreach ($person['partners'] as $partner) {
            foreach ($partner['prices'] as $price) {
                $amounts[] = $price['amount'];
            }
        }
    }
}
print_r($amounts);

输出:

Array
(
    [0] => 125
    [1] => 139
    [2] => 52
    [3] => 72
)