谁能帮我把字符串也转换成数组或JSON?请查看下面的文本样本;
{
"account_id": "dfdfdf",
"email": "mail-noreply@google.com",
"id": "dfdfdf",
"name": "Gmail Team",
"object": "contact",
"phone_numbers": []
},
{
"account_id": "dfdf",
"email": "saaddfsdfsdsfsdf@gmail.com",
"id": "dfdf",
"name": "Ab",
"object": "contact",
"phone_numbers": []
},
{
"account_id": "dfdf",
"email": "abc@gmail.com",
"id": "dfdfdf",
"name": "xyz",
"object": "contact",
"phone_numbers": []
},
我试过了
preg_match_all("/'{([^')]*)'},/", $stream[0], $aMatches);
但它不会返回任何内容。我也尝试过json_decode,json_encode但找不到任何成功。
谢谢
目标是将其转换为适当的 JSON 格式,以便您可以使用 json_decode
.我分步分解一下:
-
删除所有
'n
字符:$string = str_replace(''n', '', $string);
-
删除最后一个逗号
$string = rtrim($string, ',');
-
添加方括号
$string = "[" . trim($string) . "]";
-
将其转换为 PHP 数组:
$json = json_decode($string, true);
结果:
$string = ''; //your string
$string = str_replace(''n', '', $string);
$string = rtrim($string, ',');
$string = "[" . trim($string) . "]";
$json = json_decode($string, true);
var_dump($json);
输出:
array (size=3)
0 =>
array (size=6)
'account_id' => string '43z95ujithllc32fn02u8ynef' (length=25)
'email' => string 'mail-noreply@google.com' (length=23)
'id' => string '955xl0q3h9qe0sc11so8cojo2' (length=25)
'name' => string 'Gmail Team' (length=10)
'object' => string 'contact' (length=7)
'phone_numbers' =>
array (size=0)
empty
1 =>
array (size=6)
'account_id' => string '43z95ujithllc32fn02u8ynef' (length=25)
'email' => string 'test-email1@gmail.com' (length=21)
'id' => string '3u4e6i9ka3e7ad4km90nip73u' (length=25)
'name' => string 'Test Account 1' (length=14)
'object' => string 'contact' (length=7)
'phone_numbers' =>
array (size=0)
empty
2 =>
array (size=6)
'account_id' => string '43z95ujithllc32fn02u8ynef' (length=25)
'email' => string 'test-email@gmail.com' (length=20)
'id' => string 'bt3lphmp0g14y82zelpcf0w0r' (length=25)
'name' => string 'Test Account' (length=12)
'object' => string 'contact' (length=7)
'phone_numbers' =>
array (size=0)
empty