配列インデックス(indexプロパティ)
広告
PHPスクリプト側から渡されてきた配列のインデックス番号を参照します。「index」プロパティを使用します。
$smarty.foreach.ループ名.index
インデックス番号は「0」からとなります。「iteration」プロパティと似ていますが「index」プロパティの場合は0から開始される点に注意して下さい。
例えば次のように記述します。
{foreach from=$personaldata item=var name=loopname}
<p>{$var}[{$smarty.foreach.loopname.index}]</p>
{/foreach}
ループが1度回る度に要素とその要素が含まれる配列のインデックスを表示します。
サンプルプログラム
では簡単なサンプルプログラムを作成して試してみます。
<?php
require_once('Smarty.class.php');
$smarty = new Smarty();
$smarty->template_dir = 'd:/smartysample/foreach/templates/';
$smarty->compile_dir = 'd:/smartysample/foreach/templates_c/';
$smarty->config_dir = 'd:/smartysample/foreach/configs/';
$smarty->cache_dir = 'd:/smartysample/foreach/cache/';
$smarty->assign('title', '繰り返し処理のテスト');
$data = array(
"name"=>"Yamada",
"old"=>"24",
"address"=>"Tokyo"
);
$smarty->assign('personaldata', $data);
$smarty->display('sample5-1.tpl');
?>
上記を「sample5-1.php」の名前で「(Apacheドキュメントルート)¥smarty¥foreach」に保存します。
{* Smarty foreach/sample5-1.tpl *}
<html>
<head>
<title>Smarty Test</title>
</head>
<body>
<h1>{$title}</h1>
{foreach from=$personaldata item=var name=loopname}
<p>{$var}[{$smarty.foreach.loopname.index}]</p>
{/foreach}
</body>
</html>
上記を「sample5-1.tpl」の名前で「D:¥smartysample¥foreach¥templates」に保存します。
そしてブラウザから「http://localhost/smarty/foreach/sample5-1.php」へアクセスして下さい。
( Written by Tatsuo Ikura )
PHPBook