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

瘦欲@ 提交于 2019-12-04 06:21:13

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

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

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));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!