<?php $catalog = simplexml_load_file("cdcatalog.xml"); $totalcost = array(); $cdcount = array(); // traverse the list of cds in the catalog. For each cd perform the following // actions: // 1) extract the artist // 2) look up the artist in the totalcost array. If the artist is not there, then // insert the artist into both the totalcost array and the cdcount array // 3) increment the artist's amount in the totalcost array by the amount of the cd // and increment the artist's count in the cdcount array by 1 foreach ($catalog->cd as $cd) { foreach($cd->artist as $artist) { $artist_names = preg_split('/\s+/', $artist); $firstname = array_shift($artist_names); // if the artist has only a first name then suppress the , that separates // the last and first names if (count($artist_names) > 0) { $lastname = join(" ", $artist_names); $artist = $lastname . ", " . $firstname; } else { $artist = $firstname; } $price = (double)$cd->price; if (!array_key_exists($artist, $totalcost)) { $totalcost[$artist] = 0; $cdcount[$artist] = 0; } $totalcost[$artist] += $price; $cdcount[$artist]++; } } ksort($totalcost); printf("%-25s%s\n", "Artist", "Avg. Price"); foreach ($totalcost as $artist => $cumulative_price) { printf("%-25s%4.2f\n", $artist, $cumulative_price / $cdcount[$artist]); } ?>