連想配列

広告

配列ではキーを指定して連想配列にすることも出来ます。

$配列変数名 = array('キー文字列'=>要素, ...);

連想配列の場合も基本的な使い方はPHPで使用する場合と同じです。例えば次のように記述します。

<?php

$smarty = new Smarty();

$smarty->assign('title', 'Fruit');
$smarty->assign('fruit', array('name'=>'Lemon', 'price'=>'500'));

$smarty->display('index.tpl');

?>

上記の場合は「assign」メソッドの2番目の引数に2つの要素を持つ配列を指定しています。

次に値を割り当てられるテンプレートファイル側の記述方法です。PHPでは連想配列の各要素にアクセスする場合には次のように記述していました。

$配列変数名['キー名']

ところがテンプレートファイル内で連想配列の各要素にアクセスするには次の書式を使います。

{$配列変数名.キー名}

連想配列を使う場合だけPHPで記述する方法と異なるので注意が必要です。具体的には次のように記述します。

<html>
<head>
<title>Smarty Test</title>
</head>
<body>

<h1>{$title}</h2>
<p>Name : {$fruit.name}</p>
<p>Price : {$fruit.price}</p>

</body>
</html>

サンプルプログラム

では簡単なサンプルプログラムを作成して試してみます。

sample3-1.php

<?php

require_once('Smarty.class.php');

$smarty = new Smarty();

$smarty->template_dir = 'd:/smartysample/var/templates/';
$smarty->compile_dir  = 'd:/smartysample/var/templates_c/';
$smarty->config_dir   = 'd:/smartysample/var/configs/';
$smarty->cache_dir    = 'd:/smartysample/var/cache/';

$smarty->assign('title', 'Fruit');
$smarty->assign('fruit', array('name'=>'Lemon', 'price'=>'500'));

$smarty->display('sample3-1.tpl');

?>

上記を「sample3-1.php」の名前で「(Apacheドキュメントルート)¥smarty¥var」に保存します。

sample3-1.tpl

{* Smarty var/index3-1.tpl *}
<html>
<head>
<title>Smarty Test</title>
</head>
<body>

<h1>{$title}</h1>
<p>Name : {$fruit.name}</p>
<p>Price : {$fruit.price}</p>

</body>
</html>

上記を「sample3-1.tpl」の名前で「D:¥smartysample¥var¥templates」に保存します。

そしてブラウザから「http://localhost/smarty/var/sample3-1.php」へアクセスして下さい。

連想配列

( Written by Tatsuo Ikura )