如何遍历并访问多维和关联数组中的各种元素? PHP,JSON 或 XML

How to loop over and access various elements in an array that is both multidimentional and associative? PHP, either JSON or XML

我正在通过 API (zotero.org) 检索书目数据,它与底部的样本相似(只是更复杂 - 样本是输入的)。

我想检索一条或多条记录并在页面上显示某些值。例如,我想遍历每个顶级记录并以格式良好的引用打印数据。暂时忽略正确的围兜样式,假设我只想为返回的每条记录打印出以下内容:

作者 1 姓名、作者 2 姓名、文章标题、出版物标题、关键字

这与代码不符,因为我显然错误地引用了键值对,只会把它弄得一团糟。

如果我请求 JSON 格式,则以下布局类似于数据,但我可以请求 XML 数据。我不挑剔;我试过每一个都没有运气。

[
  {
    "key": "123456",
    "state": 100,
    "data": {
      "articleTitle": "Wombat coprogenetics: enumerating a common wombat population by microsatellite analysis of faecal DNA",
      "authors": [
        {
          "firstName": "Sam C.",
          "lastName": "Smith"
        },
        {
          "firstName": "Maxine P.",
          "lastName": "Jones"
        }
      ],
      "pubTitle": "Australian Journal of Zoology",
      "tags": [
         {
          "tag": "scary"
        },
        {
          "tag": "secret rulers of the world"
        }
      ]
   }
 },
 {
   "key": "001122",
   "state": 100,
   "data": {
     "articleTitle": "WOMBAT and WOMBAT-PK: Bioactivity Databases for Lead and Drug Discovery",
     "authors": [
        {
          "firstName": "Marius",
          "lastName": "Damstra"
        }
      ],
      "pubTitle": "Chemical Biology: From Small Molecules to Systems Biology",
      "tags": [
        {
          "tag": "Wrong Wombat"
        }
      ]
    }
  }
]

如果括号、逗号等有误,那只是我例子中的错别字,不是我问题的原因。

您尝试过使用 array_map 吗?

那会是这样的:

$entries = json_decode($json, true);
print_r(array_map(function ($entry) {
    return implode(', ', array_map(function ($author) {
        return $author['firstName'];
    }, $entry['data']['authors'])) . ', ' . $entry['data']['articleTitle'] . ', ' . $entry['key'];
}, $entries));

像这样的事情对你来说可能是一个好的开始:

$output = [];

// Loop through each entry
foreach ($data as $row) {
    // Get the "data" block
    $entry = $row['data'];
    // Start your temporary array
    $each = [
        'article title' => $entry['articleTitle'],
        'publication title' => $entry['pubTitle'],
        'key' => $row['key']
    ];
    // Get each author's name
    foreach ($entry['authors'] as $i => $author) {
        $each['author' . ++$i . ' name'] = $author['firstName'] . ' ' . $author['lastName'];
    }
    // Append it to your output array
    $output[] = $each;
}

print_r($output);

示例:https://eval.in/369313

decode your json 作为数组并将其作为任何数组进行迭代:

$json_decoded= json_decode($json,true);

$tab="\t";

foreach ($json_decoded as $key => $val) {
    echo "Article ".$val["key"]."\n" ;
    echo $tab."Authors :\n";
    foreach ($val["data"]["authors"] as $key => $author){
        echo $tab.$tab. ($key+1) ." - ".$author["firstName"]. " ".$author["lastName"]."\n";
    } 

    echo $tab."Article Title: ".$val["data"]["articleTitle"] ."\n";
    echo $tab."Publication Title: ".$val["data"]["pubTitle"] ."\n";
    echo $tab."Key: ".$val["key"]."\n";
}

run on codepad

并且您可以对 xml 使用与流动相同的方法:

$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$json_decoded = json_decode($json,TRUE);
//the rest is same

对于xml你可以使用SimpleXml的功能 或 DOMDocument class


提示

在将数据转换为数组后 api return 了解您的数据结构 在调试中使用 var_dump($your_decoded_json)