douben6670
2017-11-23 14:38
浏览 127
已采纳

在PHP中将字符串转换为关联数组

I am using PHP with cURL to make requests to an API.

The API responds with an encrypted string which I then have to use json_decode on and run it through a pre-defined decrypt method that returns a string.

So I have something like this:

echo $response; 
$decodedResponse = json_decode($response, true);

// New instance of Decrypt
$decrypt =  new Decrypt();
$decryptedResponse = $decrypt->decrypt($decodedResponse);
echo $decryptedResponse;

Using var_dump($decryptedResponse) yields string(960) but the string looks like a JSON array.

{"Title":"Mr","Forenames":"Steve"}

So what is the best way to rip apart this string so that I can use the variables through an associative array?

I had already tried:

foreach(decryptedResponse as $data)
{
    echo $data['Title'];
}

But this outputted nothing on the screen.

Am I misinterpreting the use of json_decode?

As many have stated it seems you have to decode twice, I'll look into this and share my findings.

图片转代码服务由CSDN问答提供 功能建议

我正在使用PHP和cURL向API发出请求。 </ p>

API使用加密字符串进行响应,然后我必须使用 json_decode </ code>并通过预定义的解密方法运行它,该方法返回一个字符串。</ p>

所以我有这样的事情:</ p>

  echo $ response;  
 $ decodingResponse = json_decode($ response,true); 
 
 // Decrypt的新实例
 $ decrypt = new Decrypt(); 
 $ decryptedResponse = $ decrypt-&gt; decrypt($ decodingResponse); \  necho $ decryptedResponse; 
 </ code> </ pre> 
 
 

使用 var_dump($ decryptedResponse)</ code>产生 string(960)</ code>但字符串看起来 就像一个JSON数组。</ p>

{“Title”:“Mr”,“Forenames”:“Steve”} </ code> </ p>

那么撕掉这个字符串的最佳方法是什么,以便我可以通过关联数组使用变量?</ p>

我已经尝试过了:</ p>

  foreach(decryptedResponse as $ data)
 {
 echo $ data ['Title']; 
} 
 </ code> </ pre> 
 
 

但这没有输出任何内容 屏幕。</ p>

我是否误解了 json_decode </ code>的使用?</ p>

正如许多人所说的,你似乎必须解码 两次,我会调查一下并分享我的发现。</ p> </ div>

3条回答 默认 最新

相关推荐 更多相似问题