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

时间:2015-10-06 03:57:20

标签: php arrays string

如何获得此

    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);

//正在打印“{$ array ['site']}位于pincode {$ array ['location'] ['address'] ['pincode']}”为什么它不转换$ array ['网站']进入价值。我在PHP手册上阅读并得到一些参考{}不能对返回的字符串工作然后是什么方法,以便我可以在返回字符串后打印数组值?

1 个答案:

答案 0 :(得分:1)

您可以打印您想要的字符串。

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