php-Reach空JSON数组

php-Reach空JSON数组,php,json,microsoft-cognitive,Php,Json,Microsoft Cognitive,我使用MicrosoftFaceAPI,我想向最终用户显示数据,但如何使用foreach来尝试faceAttributes->age? 这里有一个JSON文件的示例 [ { "faceId": "c5c24a82-6845-4031-9d5d-978df9175426", "faceRectangle": { "width": 78, "height": 78, "left": 394

我使用MicrosoftFaceAPI,我想向最终用户显示数据,但如何使用foreach来尝试faceAttributes->age? 这里有一个JSON文件的示例

[
    {
        "faceId": "c5c24a82-6845-4031-9d5d-978df9175426",
        "faceRectangle": {
            "width": 78,
            "height": 78,
            "left": 394,
            "top": 54
        },
        "faceAttributes": {
            "age": 71.0,
            "gender": "male",
            "smile": 0.88,
            "facialHair": {
                "mustache": 0.8,
                "beard": 0.1,
                "sideburns": 0.02
                }
            },
            "glasses": "sunglasses",
            "headPose": {
                "roll": 2.1,
                "yaw": 3,
                "pitch": 0
            }
        }
    }
]
我尝试了此代码,但不起作用:

<?php

    $json = file_get_contents('file.json');
    $data =  json_decode($json);
    if (count($data->faceAttributes)) {
        // Cycle through the array
        foreach ($data->faceAttributes as $idx => $faceAttributes) {
            // Output a row
    echo $faceAttributes->age ;
    echo $faceAttributes->gender ;

?>


谢谢

您不必使用foreach迭代对象,因为'age'是
$data->faceAttributes
本身的属性

用这个代替

if (count($data->faceAttributes)) {    
    echo $data->faceAttributes->age;
    echo $data->faceAttributes->gender;
}
但是,
$data
是一个数组,您使用的
$data
实际上是
$data[0]

所以,若数据数组中只有一个元素,那个么您可以执行以下操作:

$data = $data[0] or $data = json_decode($json)[0]

或者,如果有多个元素,您可以遍历
$data

json字符串采用类格式。(没有[],只有{})。或者使用json_decode的第二个参数将json转换为数组。或者将$data视为class.BTW,该json似乎无效。有一个太多的“}”。