php - 到达空 JSON 数组
php - Reach empty JSON array
我使用 Microsoft Face API 并且我想向最终用户显示数据,但我如何使用 foreach 来设置 faceAttributes->age ?
有一个例子 JSON file
[
{
"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
。
我使用 Microsoft Face API 并且我想向最终用户显示数据,但我如何使用 foreach 来设置 faceAttributes->age ? 有一个例子 JSON file
[
{
"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
。