简体   繁体   English

当函数返回字符串时,echo $string 不打印数组元素

[英]echo $string does not print array elements while string returned by a function

How to get this如何获得这个

    function render($string, $array)
    {
        $pattern = '/[^{{=]*[\w][}}$]/';
        preg_match_all($pattern, $string, $matches);

        foreach($matches as $tt)
        {
            $index = '';
            foreach($tt as $match1){
                $match = str_replace('}', '', $match1);

                if (strpos($match,'.') !== false)
                {
                    $string_parts = explode('.', $match);
                    //print_r($string_parts);
                    foreach($string_parts as $part)
                    {
                        $index .="['".$part."']"; 
                    }

                }
                else
                {
                    $index ="['".$match."']";
                }
                //echo '$array'.$index;
                $new_str =  str_replace("{{=".$match."}}", '{$array'.$index.'}' , $string);
                    $index = '';
                //echo $new_str;
                $string = $new_str;
            }

        }
        return $string;
    }


    $arr = [
            'site'=>'smartprix',
            'users'=>[
                        ['name'=>'user1', 'contact'=>'1234'],
                        ['name'=>'user2', 'contect'=>'4321']
                     ],
            'location'=>['address'=>['pincode'=>'123456', 'city'=>'Noida'],
                         'near'=>'mamura']
            ];

    $array = $arr;
    //echo "{$array['site']}"; //It is printing smartprix
    $string = "{{=site}} is located at pincode {{=location.address.pincode}}";

    echo render($string, $array);

// it is printing "{$array['site']} is located at pincode {$array['location']['address']['pincode']}" why it not convert $array['site'] into the value. // 它正在打印“{$array['site']} 位于密码{$array['location']['address']['pincode']}”为什么它不转换 $array['site']入值。 I read on php manual and got some reference that {} do not work on returned string then what is the method so that i can print array values after returning the string ?我阅读了 php 手册并得到了一些参考,即 {} 不适用于返回的字符串,那么方法是什么,以便我可以在返回字符串后打印数组值?

您可以打印您预期的字符串是。

 echo $string = $array['site']." is located at pincode ".$arr['location']['address']['pincode'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM