使我的功能更好

时间:2014-03-28 23:20:00

标签: javascript php html performance

我怎样才能使这段代码更有效率?网豆说我的功能太多了。还有人说我在if语句中应该引入一个新函数。有些身体可以帮助我创造一个好的功能并使我的功能更小

function dispalyEvent($weekNr, $week, $year){
    echo "<p>";
    $gendate = new DateTime();
    $gendate->setISODate($year,$week,$weekNr);

    $month = $gendate->format('m');
    $day =  $gendate->format('d');
    $event_query = mysql_query("SELECT * FROM calendar ORDER BY starttime"); 

    while($event = mysql_fetch_array($event_query)) { 
    $startYear = $event['startyear'];
    $startMonth = $event['startmonth'];
    $startDay = $event['startdate'];
    $endYear = $event['endyear'];
    $endMonth = $event['endmonth'];
    $endDay = $event['enddate'];

    $period = new DatePeriod(
            new DateTime($startYear.$startMonth.$startDay),
            new DateInterval('P1D'),
            new DateTime($endYear.$endMonth.$endDay +1)
    );

    $currentDate = $year."-".$month."-".$day;

        foreach ($period as $savedDate) {   

            if ($currentDate == $savedDate->format('Y-m-d')){
                buildEvent($event['ad'], $event['starttime'], $event['title'], $event['endtime'], $event['location'], $event['address'], $event['price'], $event['description']);
            }    
            if ($event['Approved'] == "Approved"){
                    buildEvent($event['ad'], $event['starttime'], $event['title'], $event['endtime'], $event['location'], $event['address'], $event['price'], $event['description']);
            }

        }

    }
    echo "</p>";
}
?>

2 个答案:

答案 0 :(得分:2)

除了出于安全和支持原因切换到MySQLiPDO之外;你也可以清除大部分未使用的代码。

例如:您实际上不必为每个数组值创建新变量。

这就是我要做的事情:

<?php
function dispalyEvent($weekNr, $week, $year){
    echo "<p>";
    $currentDate = new DateTime()->setISODate($year,$week,$weekNr)->format('Y-m-d');

    $event_query = mysql_query("SELECT * FROM calendar ORDER BY starttime");         
    while($event = mysql_fetch_array($event_query)) { 
        $period = new DatePeriod(
            new DateTime($event['startyear'].$event['startmonth'].$event['startday']),
            new DateInterval('P1D'),
            new DateTime($event['endyear'].$event['endmonth'].(event['$endday']+1))
        );

        foreach ($period as $savedDate) {   
            if ($currentDate == $savedDate->format('Y-m-d') || $event['Approved'] == "Approved"){
                buildEvent($event['ad'], $event['starttime'], $event['title'], $event['endtime'], $event['location'], $event['address'], $event['price'], $event['description']);
            }
        }
    }
    echo "</p>";
}
?>

答案 1 :(得分:1)

你不应该认真对待NetBeans警告,至少不是那种。其中大多数是可配置的,您可以更改它们。 这些在与团队合作时很有用,如果你想强迫&#34;强迫&#34;您的团队遵循您设置这些规则的某些规则来帮助您验证代码。

除了Tularis所说的我不知道你能做些什么。请记住,良好的代码并不总是很短,易于理解的代码就像它一样好。