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 json json

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


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 functionsor 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


Something like this might be a good start for you:

$output = [];// Loop through each entryforeach ($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


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