有人可以帮助我将字符串转换为数组或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但是找不到任何成功。
由于
答案 0 :(得分:3)
目标是将其转换为适当的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