将存储在JSON数组中的字符串转换为PHP中的变量名

时间:2018-06-04 20:16:10

标签: php json

我创建了一个JSON文件,我将其用作应用程序全局配置的数据源。

摘录自json文件

 //Have not put the complete json file. No error in the file
 {
 "loginType":[
    {
        "name":"Facebook",
        "url":"#",
        "method":"",
        "label":"Continue with Facebook",
        "type":"social",
        "class":"",
        "icon":"",
        "callBack_url" : "fbLoginUrl",
        "providerButton":"<div class='fb-login-button' data-max-rows='1' 
        data-size='large' data-button-type='continue_with' data-use- 
        continue-as='true'></div>"        
    },
    {
        "name":"Twitter",
        "url":"#",
        "method":"logInWithTwitter()",
        "label":"Continue with Twitter",
        "type":"social",
        "class":"",
        "icon":"",
        "callBack_url" : "twitterLoginUrl",
        "providerButton" :""
      }
    ]
}

json文件中的callBack_url键有一个类似名称的变量,其值为url,例如$ twitterLoginUrl =“https://some.site.com/twitter_login?param1

$jsonData_signIn =json_decode
(file_get_contents(/path/to/oauth2_provider.json)); 
 $oauth2Provider = jsonData_signIn->loginType;
       foreach($oauth2Provider as $type){
         if($type->type == 'local' ){
           echo "<a href=\"{$type->callBack_url}\">{$type->label}</a>";
         }
    }    

对于上述内容,作为链接的输出,我得到例如<a href="$fbLoginURL">Continue with facebook</a>

echo "<a href=\"{${$type->callBack_url}}\">{$type->label}</a>";

我没有存储完整URI的原因是我将动态生成一些参数。

1 个答案:

答案 0 :(得分:2)

查看变量变量手册:http://php.net/manual/en/language.variables.variable.php

您基本上只是将字符串变量名称包装在$ {}中,以使其行为类似于实际变量。

$fbLoginUrl = 'https://www.facebook.com/v2.10/dialog/oauth?client_id=xxxxxxx&state=xxxxxxx&response_type=code&sdk=php-sdk-5.6.2&redirect_uri=some.site.com/fbLogin.php&scope=public_profile';
$json = '{"callBack_url" : "fbLoginUrl"}';
$decoded = json_decode($json);
echo ${$decoded->callBack_url};