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

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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).

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

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.

[
  {
    "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.

How to&Answers:

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

$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 = 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


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

Answer:

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

Answer:

Have you tried to use 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));