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

时间:2022-07-05 21:36:07

I'm retrieving bibliographic data via an API (zotero.org), and it is similar to the sample at the bottom (just way more convoluted - sample is typed).

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

I want to retrieve one or more records and display certain values on the page. For example, I would like to loop through each top level record and print the data in a nicely formated citation. Ignoring the proper bib styles for the moment, let's say I want to just print out the following for each record returned:

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

author1 name, author2 name, article title, publication title, key

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

This doesn't match the code, because I've clearly been referencing the key value pairs incorrectly and will just make a mess of it.

这与代码不匹配,因为我显然错误地引用了键值对,并且只会弄乱它。

The following is laid out like the data if I request JSON format, though I can request XML data instead. I'm not picky; I've tried using each with no luck.

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

If there is a mistake in brackets, commas, etc. it is just a typo in my example and not the cause of my issue.

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

3 个解决方案

#1


6  

decode your json as array and iterate it as any array as flowing:

将您的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

and you can use the same method for xml as flowing:

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

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

for xml you can use the SimpleXml's functions or DOMDocument class

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


Tip

to know the structure of your data that api return to you after it converted to array use var_dump($your_decoded_json) in debuging

知道你转换为数组后返回给你的数据结构使用var_dump($ your_decoded_json)进行调试

#2


3  

Something like this might be a good start for you:

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

$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);

Example: https://eval.in/369313

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

#3


3  

Have you tried to use array_map ?

你试过使用array_map吗?

That would be something like:

这将是这样的:

$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));

#1


6  

decode your json as array and iterate it as any array as flowing:

将您的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

and you can use the same method for xml as flowing:

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

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

for xml you can use the SimpleXml's functions or DOMDocument class

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


Tip

to know the structure of your data that api return to you after it converted to array use var_dump($your_decoded_json) in debuging

知道你转换为数组后返回给你的数据结构使用var_dump($ your_decoded_json)进行调试

#2


3  

Something like this might be a good start for you:

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

$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);

Example: https://eval.in/369313

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

#3


3  

Have you tried to use array_map ?

你试过使用array_map吗?

That would be something like:

这将是这样的:

$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));