打印嵌套JSON数组值[重复]

6ojccjat  于 2022-12-05  发布在  其他
关注(0)|答案(1)|浏览(251)

此问题在此处已有答案

How to extract and access data from JSON with PHP?(1个答案)
3小时前关门。
我一直在试图找到打印个人数据的方法,但似乎找不到哪里出错了。
我从这个开始,但是没有得到任何结果。在此之前,我尝试过嵌套循环,但是也没有得到任何结果。

$data = curl_exec($ch);
$d = json_decode($data, true);
foreach($d as $k=>$v){
echo $v['value']['displayName'];
}

然后我尝试了下面的方法,只得到了一些结果。我不知道我在哪里出了问题。

foreach(json_decode($data,true) as $d){
 foreach($d as $k=>$v){
  foreach($v as $kk=>$vv){
   echo $kk.$vv;
   }
  }
}

JSON如下所示:

{
  "value": [
    {
      "id": "",
      "name": "",
      "etag": "",
      "type": "Microsoft.SecurityInsights/alertRules",
      "kind": "Scheduled",
      "properties": {
        "incidentConfiguration": {
          "createIncident": true,
          "groupingConfiguration": {
            "enabled": false,
            "reopenClosedIncident": false,
            "lookbackDuration": "PT5M",
            "matchingMethod": "AllEntities",
            "groupByEntities": [],
            "groupByAlertDetails": null,
            "groupByCustomDetails": null
          }
        },
        "entityMappings": [
          {
            "entityType": "Account",
            "fieldMappings": [
              {
                "identifier": "FullName",
                "columnName": "AccountCustomEntity"
              }
            ]
          },
          {
            "entityType": "IP",
            "fieldMappings": [
              {
                "identifier": "Address",
                "columnName": "IPCustomEntity"
              }
            ]
          }
        ],
        "queryFrequency": "P1D",
        "queryPeriod": "P1D",
        "triggerOperator": "GreaterThan",
        "triggerThreshold": 0,
        "severity": "Medium",
        "query": "",
        "suppressionDuration": "PT1H",
        "suppressionEnabled": false,
        "tactics": [
          "Reconnaissance",
          "Discovery"
        ],
        "displayName": "MFA disabled for a user",
        "enabled": true,
        "description": "Multi-Factor Authentication (MFA) helps prevent credential compromise. This alert identifies when an attempt has been made to diable MFA for a user ",
        "alertRuleTemplateName": null,
        "lastModifiedUtc": "2022-11-14T02:20:28.8027697Z"
      }
    },
...
...
...
vltsax25

vltsax251#

下面是不需要循环就可以得到显示名称的方法。注意0是数组的键值,因为它没有名称。
我们从value开始,选择第一个数组0,再深入一层。现在我们需要选择properties,最后,我们可以从那里得到displayName

$displayName = $d["value"][0]["properties"]["displayName"];
echo($displayName);

/*
Here is a quick demonstration:

value:
{
    0:
    {
        ...
        properties:
        {
            ...
            displayName: [We made it!]
        }
    }

}

*/

这里有一个非常好的帖子,更详细地解释了这一点
How to decode multi-layers nested JSON String and display in PHP?

相关问题