<?php
/*************************************************************************************************
Name    high_scored.php
Action    アンケートのスコア順にエントリーを並べ替えて一覧リンクを表示する。
    
                                2008.03.23 Ver.0.01  Genki wrote

    仕様
    Ver.0.01    とりあえず。
        
***************************************************************************************************/
//各種設定
mb_internal_encoding("euc-jp");
mb_http_output("UTF-8");

$maxline 5;    //上位何位まで表示するか。

//Scoreを取り出す
$ratio = array(    'a' => '2',
        
'b' => '1',
        
'c' => '0',
        
'd' => '-2',
        
'e' => '-2'
);
$table "questionnaire";

if(
$cn pg_connect("host=hogehoge.hoge port=**** user=hogehoge")){        //接続成功したら
    
$rs pg_query("select id,a,b,c,d,e from $table where a+b+c+d+e!=0;");        //投票のある行を読む
    
$ct pg_num_rows($rs);                        //データ数を得る
    
pg_close($cn);
}else{
    echo 
"データベースに接続できませんでした。<br>\n";        //エラー
}

for(
$i=0;$i<$ct;$i++){
    
$item pg_fetch_array($rs,$i,PGSQL_ASSOC);                    //スコア情報を配列に格納
    
$year substr($item['id'],0,4);
    
$month substr($item['id'],5,2);
    
$entry[$i]['basename'] = substr($item['id'],8);            //2次元配列$entryに、basename,url,scoreを代入。
    
$entry[$i]['url'] = "/{$year}/{$month}/{$entry[$i]['basename']}.php";
    
$entry[$i]['score'] = $ratio['a'] * $item['a']
                 +
$ratio['b'] * $item['b']
                 +
$ratio['c'] * $item['c']
                 +
$ratio['d'] * $item['d']
                 +
$ratio['e'] * $item['e'];
    
}

usort($entry,sortbyscore);
    
/*** scoreで降順にソートするための関数 ***/
    
function sortbyscore($a,$b){
        if(
$a['score'] == $b['score']){
            return 
0;
        }elseif(
$a['score'] > $b['score']){
            return -
1;
        }elseif(
$a['score'] < $b['score']){
            return 
1;
        }
    }


//エントリーのタイトルと投稿日を取得
$dbname "movabletype1";        //MT用のデータベース名
$table "mt_entry";            //エントリ情報が入ってるテーブル

if($cn pg_connect("host=hogehoge.hoge port=**** user=hogehoge dbname=$dbname")){        //接続成功したら
    
for($i=0;$i<$maxline;$i++){                                //取得最大行数まで
        
$rs pg_query("select entry_title,entry_created_on from $table where entry_basename='{$entry[$i]['basename']}'");
        
$item pg_fetch_array($rs,0,PGSQL_NUM);                    //タイトルと投稿日時を配列に格納
        
$entry[$i]['title'] = $item[0];
        
$entry[$i]['date'] = str_replace("-","/",substr($item[1],2,8));        //日時は、YY/MM/DDに変換
    
}
}else{
    echo 
"データベースに接続できませんでした。<br>\n";        //エラー
}

//結果出力
for($i=0;$i<$maxline;$i++){        //最大行数まで適当なフォーマットで出力
    
echo "[{$entry[$i]['date']}]<a href=\"{$entry[$i]['url']}\">{$entry[$i]['title']}</a><font color=\"blue\">({$entry[$i]['score']}points)</font><br />\n";
}

?>