我正在构建一个交互式地图应用程序,数据库相对较小,约为11mb。然而,它有很多行数据要求我将它们分类到县和年。
我的页面加载速度大约是10-11秒,试图浏览所有这些数据并将其组织起来,然后我可以使用名为mapael的javascript库加载它。
如果有任何办法,我需要一些帮助来尝试更快地提高页面加载速度。查询似乎并不是问题所在。我认为导致问题的数据更多。
<?php
$mydb = new wpdb('uofimap_data','ob2UoV2X5tNz','uofimap_data','localhost');
$data = $mydb->get_results('
SELECT state,county,ship_date,total_cost, quantity FROM data
ORDER BY county ASC, ship_date ASC
');
$dataArray = array(
2006 => '',
2007 => '',
2008 => '',
2009 => '',
2010 => '',
2011 => '',
2012 => '',
2013 => '',
2014 => '',
);
$prevCounty = null;
$prevState = null;
$prevYear = null;
$countySum = null;
$quantitySum = null;
foreach ($data as $obj) :
//temp array to push everything into dataArray for year structure and keep all data in tact.
$tempArray = array();
//all the information to use for use
$date = date('Y', strtotime($obj->ship_date));
$state = $obj->state;
$county = $obj->county;
$cost = $obj->total_cost;
$quantity = $obj->quantity;
//Print only the needed values which is the sums of that county for that particular year.
if($prevCounty == $county){
if($prevYear == $date){
} else {
array_push($tempArray, $prevCounty, $prevState, $countySum, $quantitySum);
$dataArray[$prevYear][] = $tempArray;
}
} else {
if($prevCounty == null){
//Only needed if first value in database is a solo county / year.
//echo $county . ', ' . $state . ' : ' . $cost . ' ' . $date . ' New Null<br>';
} else {
array_push($tempArray, $prevCounty, $prevState, $countySum, $quantitySum);
$dataArray[$prevYear][] = $tempArray;
}
}
//Set everything
if($prevCounty == $county){
if($prevYear == $date){
$countySum += $cost;
$quantitySum += $quantity;
//echo $county . ' ' . $countySum . ' '. $state . ' ' . $date . ' ' . $quantitySum . ' Previous Year<br>';
} else {
$countySum = $cost;
$quantitySum += $quantity;
//echo $county . ' ' . $countySum . ' '. $state . ' ' . $date . ' ' . $quantitySum . ' Current Year<br>';
}
} else {
$countySum = $cost;
$quantitySum = $quantity;
//echo $county . ' ' . $countySum . ' '. $state . ' ' . $date . ' ' . $quantitySum . ' New County <br>';
}
$prevCounty = $county;
$prevState = $state;
$prevYear = $date;
endforeach;
$mapaelJson = '<script type="text/javascript">';
$mapaelJson .= 'data={';
foreach($dataArray as $key => $value){
$mapaelJson .= '"' . $key . '": {';
$mapaelJson .= '"areas":{';
foreach($value as $key1 => $value1){
$county = $value1[0];
$county = ucwords(strtolower($county));
$state = $value1[1];
$total = $value1[2];
$quantity = $value[3];
//var_dump($value1);
$mapaelJson .= '"'.$county . ', '. $state . '" : {';
$mapaelJson .= '"county" : "' . $county . '",';
$mapaelJson .= '"value" : "' . $total . '",';
$mapaelJson .= '"quantity" : "' . $quantity . '",';
$mapaelJson .= '},';
}
$mapaelJson .= '} },';
}
$mapaelJson .= '};</script>';
echo $mapaelJson;
?>
答案 0 :(得分:0)
你有没有看过剖面仪?如果您可以使用免费版本的Blackfire.io或使用xdebug的cachegrind文件创建跟踪,这将为您提供最佳的优化思路。
无论如何,暂时你肯定需要减少循环和内循环的数量。此外,尽可能多地尝试减少压痕(保持较低的级别以获得更高的可读性)。你可以经常在循环中使用continue
,这通常有帮助。