PHP:如何使用引号解码json字符串

时间:2016-08-18 18:39:22

标签: php arrays json string

服务器返回如下字符串:

string(150) ""\"{ 'success': false, 
'message': Email address already registered, 
'error': { 'code': 100, 
           'message': 'Email address already registered!' }}\"""

在结果上调用 json_decode 并不会将字符串更改为数组,它只是一个字符串。

如何修复此字符串以转换为PHP数组?

2 个答案:

答案 0 :(得分:0)

如果您仍需要从该字符串中获取let test = multiKey([ ['north', 'up'], ['south', 'down'], ['east', 'left'], ['west', 'right'] ]); test.north = 42; test.down = 123; test.up; // returns 42 test.south; // returns 123 let count = 0; for (let key in test) { count += 1; } count === 4; // true; only unique (un-linked) properties are looped over success个键的值,请使用messagepreg_match_all函数使用以下方法:

array_combine

输出:

$str = "\"{ 'success': false, 
'message': Email address already registered, 
'error': { 'code': 100, 
           'message': 'Email address already registered!' }}\"";

preg_match_all("/'(?<k>success|message)':(?<v>[^,]+)(?=,)/", $str, $matches);
$result = array_combine($matches['k'], $matches['v']);

print_r($result);

答案 1 :(得分:0)

试试这个。!!!

        $string = ""\"{ 'success': false, 
        'message': 'Email address already registered', 
        'error': { 'code': 100, 
                   'message': 'Email address already registered!' }}\""";

       $replace_hash_string =  str_replace("\","",$string);
       $final_string =  str_replace('"""','',$replace_hash_string);

       $converted_array = json_decode($final_string);

       echo "<pre>";
       print_r($converted_array);
       echo "</pre>";

希望这会有所帮助。!!!