PHP - 我的代码有效吗?

时间:2013-01-19 20:16:12

标签: php loops

我基本上从各种API获取数据并使用PHP将它们组合在一起 - 就像Web mashup一样。我目前正在使用4个foreeach语句将收集的数据插入到各自的数组中。我相信当前的代码是低效的,因为加载显示PHP数据的页面大约需要3秒钟。在过去,我只有一个大的foreach循环来同时浏览所有数据并打印它们。但这对我来说效率低下。

那么如何更快地处理代码呢?我见过一些mashup网站,例如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;

}

2 个答案:

答案 0 :(得分:3)

由于多个foreach循环,你的代码很可能并不慢(老实说,你不会觉得在现实场景中有所不同)。你在这里受到的伤害是从外部网站下载内容。

我的解决方案是每隔5分钟自动下载一次(通过cronjob,或者只是当用户访问页面时),如果不到5分钟,则显示放置在服务器上的缓存版本。 / p>

那说,这似乎是一个搜索,所以结果很可能不会发生很大变化。也许有1天的缓存而不是? (每个新的搜索查询仍然需要3秒,但如果您希望许多用户进行相同的查询,那么这将使您的网站看起来更快)。

在代码中测试 where 的简单方法是使用microtime函数在时间上出错。我通常做的是这样的事情:

$beforeCall = microtime(true);
$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");
echo "The call took " . number_format(microtime(true) - $beforeCall, 4) . " seconds";

如果你正在使用XML(看起来像),你可以使用SimplePie启用缓存。一篇很好的文章是SimplePie's own article on their cache system,您可以使用set_cache_duration调整缓存持续时间。

答案 1 :(得分:2)

缓存

最重要的是,你缺少的是缓存。缓存api调用结果的简单实现是:

$url = "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";
$cacheFile = md5($url) . '.xml';

// If the cache file exists and is less than an hour old - use it.
if (file_exists($cacheFile) && filemtime($cacheFile) > (time() - 3600)) {
    $xml = file_get_contents($cacheFile);
// else download it
} else {
    $xml = file_get_contents($url);
    file_put_contents($cacheFile, $xml);
}
$xml = simplexml_load_file($cacheFile);

即。不要在每个请求上说api - 与它交谈一次,并且只要你认为适当/安全考虑有效就使用响应(在上面的示例中为3600秒 - 或者一小时)。

这种逻辑最好封装在方法中。

DRY代码执行

与缓存相比不太重要,问题中的代码是4个相互反馈的foreach循环 - 这不是编写这种逻辑的有效方法。最好将不要重复应用于执行代码,即:

foreach($echonest_xml->artists->artist as $artist){
    ...
    $full_deezer_id[] = $artist->foreign_ids->foreign_id->foreign_id;
}

foreach($full_deezer_id as $key => $value){ // <--
    ...
    $deezer_id[] = (string)$id[1];
}

foreach($deezer_id as $id_index => $id){ // <--
    ...
}

foreach($deezer_id as $key => $value){ // <--

可以更好地写成

foreach($echonest_xml->artists->artist as $artist){
    processArtist($artist);
}

foreach($buidThis as $row) {

因此,编写代码最多循环两次(但最好只需一次),而不是相同数据的四次。

仅使用问题中的逻辑,例如前两个循环可以轻松组合:

foreach($echonest_xml->artists->artist as $artist){
    preg_match('#deezer:artist:([A-Z,a-z,0-9]+)#', $artist->foreign_ids->foreign_id->foreign_id, $id);
    $deezer_id[] = (string)$id[1];
}

应对所有代码应用相同的分析:尝试限制迭代/递归逻辑的数量。