簡體   English   中英

遞歸函數在smarty插件目錄中調用用戶創建的smarty函數

[英]Resursive function calling in user created smarty functions in smarty plugin directory

我正在嘗試在smarty插件目錄中編寫一個smarty函數。 這是一個遞歸函數。 它在普通的php文件中運行良好,並且會生成一個下拉選擇框。 現在,我想使其成為一個聰明的函數,並想從tpl中調用它。

            <?php
        /*
        * Smarty plugin
        * ————————————————————-
        * File:     function.recurse_array.php
        * Type:     function
        * Name:     recurse_array
        * Purpose:  prints out elements of an array recursively
        * ————————————————————-
        */

        function smarty_function_recurse_array($arr,$depth=0, &$smarty)
        {
            $html = '';
                    foreach ( $arr as $v ) {

                        $html.= '<option value="' . $v['id'] . '">';
                        $html.= str_repeat('-', $depth);
                        $html.= $v['cata_name'] . '</option>' . PHP_EOL;

                        if ( array_key_exists('subcategories', $v) ) {
                            $html.= smarty_function_recurse_array($v['subcategories'], $depth+1);
                        }
                    }

                    return $html;
        }

此文件存儲在smarty插件目錄中,並希望以

{recurse_array array=$myarray}

現在我對遞歸調用函數參數部分感到困惑

$html.= smarty_function_recurse_array($v['subcategories'], $depth+1);

它生成警告

Warning: Missing argument 3 for smarty_function_recurse_array()

我該如何解決?

嘗試這個:

<?php

/*
* Smarty plugin
* ————————————————————-
* File:     function.recurse_array.php
* Type:     function
* Name:     recurse_array
* Purpose:  prints out elements of an array recursively
* ————————————————————-
*/

function smarty_function_recurse_array($params, &$smarty)
{
    $depth = isset($params['depth'])?$params['depth']:0;

    $html = '';
    foreach ( $params['array'] as $v ) {    
        $html.= '<option value="' . $v['id'] . '">';
        $html.= str_repeat('-', $depth);
        $html.= $v['cata_name'] . '</option>' . PHP_EOL;

        if ( array_key_exists('subcategories', $v) ) {
            $html.= smarty_function_recurse_array(array ('array' => $v['subcategories'], 'depth' => $depth + 1), $smarty);
        }
    }

    return $html;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM