我基本上是从各种 API 获取数据并使用 PHP 将它们组合在一起 - 就像网络混搭一样。我目前正在使用 4 个 foreeach 语句将收集到的数据插入到它们各自的数组中。我认为当前代码效率低下,因为加载显示 PHP 数据的页面可能需要大约 3 秒。在过去,我只有一个大的 foreach 循环来一次遍历所有数据并打印它们。但这对我来说也感觉效率低下。
那么我怎样才能让我的代码在处理速度更快方面更有效率呢?我见过一些混搭网站,例如Soundeer,加载时间大约为一秒钟。那是因为他们的代码效率吗?
我正在使用的代码是:
$echonest_uri = simplexml_load_file("http://developer.echonest.com/api/v4/artist/search?api_key=$APIkey&style=rap&results=10&start=$element_num&bucket=id:deezer&bucket=images&sort=familiarity-desc&format=xml");
//Swap the comments for when in UWE or not
//$echonest_xml = new SimpleXMLElement($echonest_uri);
$echonest_xml = $echonest_uri;
$artist_name = array();
$artist_image = array();
$echonest_id = array();
$full_deezer_id = array();
$deezer_id = array();
$num_of_albums = array();
//Loop through each entries in the id_arr and make each image of the artist a link to the album page passing all the relevant information.
foreach($echonest_xml->artists->artist as $artist){
$artist_name[] = $artist->name;
$artist_image[] = $artist->images->image[0]->url;
$echonest_id[] = $artist->id;
$full_deezer_id[] = $artist->foreign_ids->foreign_id->foreign_id;
}
foreach($full_deezer_id as $key => $value){
preg_match('#deezer:artist:([A-Z,a-z,0-9]+)#', $value, $id);
$deezer_id[] = (string)$id[1];
}
foreach($deezer_id as $id_index => $id){
$deezer_xml = simplexml_load_file("http://api.deezer.com/2.0/artist/$id/albums&output=xml");
$num_of_albums[] = $deezer_xml->total;
}
//The variable which will contain the HTML code to display the artists.
$output = null;
foreach($deezer_id as $key => $value){
$fav_count_query = "SELECT COUNT(user_index) FROM fav_artist WHERE artist_deezer_id = '$value'";
$fav_count_resource = $mysqli->query($fav_count_query);
$fav_count = $fav_count_resource->fetch_assoc();
$output .= <<<HERE
<div class="artist-container">
<a href="albums.php?echonest_id={$echonest_id[$key]}&deezer_id={$deezer_id[$key]}&artist_name={$artist_name[$key]}&artist_image={$artist_image[$key]}&num_of_albums={$num_of_albums[$key]}" class="artist-image">
<img src="{$artist_image[$key]}" alt="{$artist_name[$key]}" title="{$artist_name[$key]}"/>
</a>
<a href="albums.php?echonest_id={$echonest_id[$key]}&deezer_id={$deezer_id[$key]}&artist_name={$artist_name[$key]}&artist_image={$artist_image[$key]}&num_of_albums={$num_of_albums[$key]}" class="artist-name">
{$artist_name[$key]}
</a>
<a href="albums.php?echonest_id={$echonest_id[$key]}&deezer_id={$deezer_id[$key]}&artist_name={$artist_name[$key]}&artist_image={$artist_image[$key]}" class="album-number">Albums:
{$num_of_albums[$key]}
</a>
</div>
HERE;
}