共通関数はTemplate/Element の中にctpファイルで作成します。ここではmodule.ctpとして、英語から日本語への変換処理を書きます。
<?php
function convert($main){
switch($main){
case 'Clear':
return "晴れ<img src=\"img/icon01.png\">";
break;
case 'Clouds':
return "曇<img src=\"img/icon02.png\">";
break;
case 'Rain':
return "雨<img src=\"img/icon03.png\">";
break;
default:
echo $main;
}
}
function convert2($description){
switch($description){
case 'clear sky':
return "晴天<br>";
break;
case 'scattered clouds':
return "きれぎれに浮かんでいる雲";
break;
case 'broken clouds':
return "ちぎれた雲<br>";
break;
case 'few clouds':
return "少しの雲<br>";
break;
case 'light rain':
return "小雨<br>";
break;
default:
echo $description;
}
}
?>
Viewの共通処理の為、viewのctp(index.ctp)に1行 $this->element(‘module’) を追加します。
<?php
$this->assign('title', '丸の内の天気');
?>
<?= $this->element('module'); ?>
<h1>丸の内の天気</h1>
<table class="table1">
<tr>
<?php
$i = 1;
foreach ($marunouchis as $marunouchi){
echo "<td width=\"150px\">";
echo h($marunouchi->forecast). "<br>";
echo convert(($marunouchi->main))."<br>";
echo convert2(($marunouchi->description))."<br>";
echo "気温".h($marunouchi->temp)."<br>";
echo "湿度". h($marunouchi->humidity)."%<br>";
echo "雲の量".h($marunouchi->cloud)."<br>";
echo "風速".h($marunouchi->speed)."m<br>";
echo "<td>";
if($i % 8 == 0){
echo "</tr><tr>";
}
$i++;
}
?>
</tr>
</table>
おおお、なるほど

夜中の晴れは”月”のアイコンにしてみましょう。
<?php
$i = 1;
foreach ($marunouchis as $marunouchi){
echo "<td width=\"150px\">";
echo h($marunouchi->forecast)."<br>";
$date = h($marunouchi->forecast);
$result = substr($date, -8);
if($result == ' 9:00 PM' or $result == '12:00 AM' or $result == ' 3:00 AM'){
echo convert3(($marunouchi->main))."<br>";
} else {
echo convert(($marunouchi->main))."<br>";
}
echo convert2(($marunouchi->description))."<br>";
echo "気温".h($marunouchi->temp)."<br>";
echo "湿度". h($marunouchi->humidity)."%<br>";
echo "雲の量".h($marunouchi->cloud)."<br>";
echo "風速".h($marunouchi->speed)."m<br>";
echo "<td>";
if($i % 8 == 0){
echo "</tr><tr>";
}
$i++;
}
?>

