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



我通过API (zotero.org)检索书目数据,它类似于底部的样本(只是方式更复杂-样本是键入的)。

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

author1名称,author2名称,文章标题,出版物标题,密钥

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

如果我请求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"
        }
      ]
    }
  }
]

如果括号,逗号等有错误,这只是我的例子中的一个打字错误,而不是我的问题的原因。

将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";
}

在codepad上运行

,您可以对XML使用相同的方法:

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

对于xml,可以使用SimpleXml的函数或DOMDocument类


提示

要了解api转换为数组后返回给您的数据的结构,请在调试

时使用var_dump($your_decoded_json)

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

$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

您是否尝试过使用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));

相关内容

  • 没有找到相关文章

最新更新