3流プログラマのメモ書き

元開発職→社内SE→派遣で営業支援の三流プログラマのIT技術メモ書き。 このメモが忘れっぽい自分とググってきた技術者の役に立ってくれれば幸いです。(jehupc.exblog.jpから移転中)

(PHP)Smartyで連想配列をアサインした場合

PHP側からDBで取得した値を2次元連想配列としてアサインしたときに、Smartyテンプレートにどう書くかです。

ドットで(.)で連想配列名(クォーテーションなし)でアクセスできるようです。

●テンプレート側

{section name=iCnt loop=$inputAry}

1列目:{$inputAry[iCnt].id} 2列目:{$inputAry[iCnt].name}

{/section}

PHP側(MySQLからデータ取得後に、2次元配列つくりテンプレートにアサイン)

//MySQLからデータ取得した後

$resAry = array();

while ($row = mysql_fetch_assoc($result)) {

array_push($resAry ,array("id" => $row["id"] , "name" => $row["name"]));

}

 

//Smarty読み込み

require_once('../../smarty/Smarty.class.php');

//Smartyオブジェクト作成

$smarty = new Smarty();

//Smartyがらみのディレクトリ設定

$smarty->template_dir = "../../smarty/templates";

$smarty->compile_dir = "../../smarty/templates_c";

$smarty->cache_dir ="../../smarty/cache";

//アサイ

$smarty->assign("inputAry", $resAry);

//テンプレート表示

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

参考:

PHPSPOT開発日誌:Smarty徹底入門(3):assignした配列を読み込む