Php 如何将此数组拆分为单独的变量?

Php 如何将此数组拆分为单独的变量?,php,arrays,variables,split,Php,Arrays,Variables,Split,当我放置print\u r($response)时,我从服务器收到此响应: 我试过使用: list($var1, $var2,$var3)=explode(",", $response); 但结果是: $var1= {"success":true; $var2= "title_response":"SUCCESS"; $var3= text_response":"any text"}}; 我需要结果: $var1= true; $var

当我放置print\u r($response)时,我从服务器收到此响应:

我试过使用:

     list($var1, $var2,$var3)=explode(",", $response);
但结果是:

     $var1= {"success":true;
     $var2= "title_response":"SUCCESS";
     $var3= text_response":"any text"}};
我需要结果:

    $var1= true;
    $var2= "SUCCESS";
    $var3= "any text";

有什么想法吗?

这是一个JSON字符串,您可以使用
JSON\u decode
的组合来转换为一个对象,然后
get\u object\u vars
以数组的形式获取对象的变量:

list($var1, $var2, $var3) = get_object_vars(json_decode($response));

echo $var2;   // SUCCESS

如注释中所述,只有当字符串是有效的JSON时,这才有效。我假设在编写问题时出现复制/粘贴错误,并且您确实拥有有效的JSON。

这是一个JSON字符串,您可以使用
JSON\u decode
组合来转换为对象,然后
get\u object\u vars
以数组形式获取对象的变量:

list($var1, $var2, $var3) = get_object_vars(json_decode($response));

echo $var2;   // SUCCESS

如注释中所述,只有当字符串是有效的JSON时,这才有效。我假设在编写问题时出现复制/粘贴错误,并且您确实拥有有效的JSON。

您可以按如下方式解析它:

// Problem data (with unbalanced { }'s)
$response = '{"success":true,"title_response":"SUCCESS","text_response":"any text"}}';

// Remove trailing '}}'
$response = substr($response, 0, -2);

// Split on the commas
$temp = explode(',', $response);

// For each element in the array, split on the colon, and take second part
array_walk($temp, function(&$value) {
  $value = explode(":", $value)[1];
});

// Distribute array into your variables
list($var1, $var2, $var3) = $temp;
但这是非常脆弱的代码。如果字符串中有逗号或冒号,它将以各种方式中断


最好获得一个有效的JSON响应,并使用适当的JSON函数对其进行解析,如@Madbreaks所述。

您可以按如下方式对其进行解析:

// Problem data (with unbalanced { }'s)
$response = '{"success":true,"title_response":"SUCCESS","text_response":"any text"}}';

// Remove trailing '}}'
$response = substr($response, 0, -2);

// Split on the commas
$temp = explode(',', $response);

// For each element in the array, split on the colon, and take second part
array_walk($temp, function(&$value) {
  $value = explode(":", $value)[1];
});

// Distribute array into your variables
list($var1, $var2, $var3) = $temp;
但这是非常脆弱的代码。如果字符串中有逗号或冒号,它将以各种方式中断


最好获得一个有效的JSON响应,并使用适当的JSON函数对其进行解析,如@Madbreaks所述。

这不是一个真正的答案,但这应该有助于它是一个JSON编码的字符串(主要是。有一个额外的大括号,可能是粘贴问题?)。用于获取数据。@aynber它不是有效的json_编码字符串。
{}
不平衡。(除非这是问题帖子中的一个输入错误。)不是真正的答案,但这应该有帮助,因为它是一个json_编码的字符串(大多数情况下。有一个额外的大括号,可能是粘贴问题?)。用于获取数据。@aynber它不是有效的json_编码字符串。
{}
不平衡。(除非这是问题帖子中的输入错误。)感谢您的回复,我在C:\xampp\htdocs\elyo\date.php在线上收到了这个错误:注意:未定义的偏移量:2179@HernánDavidGómezS
date.php
?我不知道这与这个答案有什么关系。感谢您的回复,我收到了这个错误:注意:C:\xampp\htdocs\elyo\date.php中的未定义偏移量:2179@HernánDavidGómezS
date.php
?我不明白这和这个答案有什么关系。