Get_post_meta字符串数组到数组

时间:2016-07-16 07:08:34

标签: php arrays wordpress

我正在尝试将$customFieldName转换为数组,但我将其作为字符串返回。我尝试了以下方法:

1尝试

    $field = array();
    $field = get_post_meta((int)$id[0], $customFieldName, true);

2尝试

    $field = array();
    $field = unserialize(get_post_meta((int)$id[0], $customFieldName, true));

我回来的字符串如下所示:

  

“{\” use_own_api \ “:假,\” google_auth_code \ “:\” 4 \ / hLXqq9X7sX1sOY-K6MhpEZu6bc8fGGADKLnjlcWA-P4 \ “\ ”google_api_key \“:\ ”AIzaSyAJjpxVYfZ0WQPZSPr72DOuKU3X-sXquqM \“,\” google_client_id \ “:\” 180054848980.apps.googleusercontent.com \”,\ “google_client_secret \”:\ “sdfsd \”,\ “google_access_token \”:\ “{\\” \\的access_token “:\\” ya29.Ci8YA6- sfsd-asdfas \\ “\\ ”token_type \\“:\\ ”承载\\“,\\ ”expires_in \\“:3600,\\ ”refresh_token \\“:\\” 1 \ / 534ewsdcy \\ “\\ ”创建\\“:1467867036} \”,\ “ga_active_web_property \”:{\ “__ PHP_Incomplete_Class_Name \”:\ “Google_Webproperty \” \ “帐户ID \”:\ “7489234 \”,\“childLink \ “:{\” __ PHP_Incomplete_Class_Name \ “:\” Google_WebpropertyChildLink \ “\ ”HREF \“:\” HTTPS:\ / \ / www.googleapis.com \ /分析\ / V3 \ /管理\ /账户\ / 7489234 \ /网络载体\ / UA-7489234-1 \ /简档\”,\ “类型\”:\ “分析#型材\”},\ “创建\”:\ “2016-06-28T19:38:17.530Z \” ,\ “ID \”:\ “UA-7489234-1 \”,\ “industryVertical \”:\ “COMPUTERS_AND_ELECTRONICS \”,\ “internalWebPropertyId \”:\ “11922adsf \”,\ “那种\”:\“分析#webproperty \ “\” 乐VEL \ “:\”“

然而,我仍然把它作为字符串取回来。

任何建议,如何将数组恢复为array

感谢您的回复!

1 个答案:

答案 0 :(得分:2)

我复制你的字符串但是将两个斜杠\\替换为三个\\\(我只是将你的字符串正确地复制到我的php代码引号中)然后我在字符串的末尾添加两个}}(看看在下面的代码中结束$ st)以获得有效的json - 之后我能够得到数组:

$st = '{\"use_own_api\":false,\"google_auth_code\":\"4\/hLXqq9X7sX1sOY-K6MhpEZu6bc8fGGADKLnjlcWA-p4\",\"google_api_key\":\"AIzaSyAJjpxVYfZ0WQPZSPr72DOuKU3X-sXquqM\",\"google_client_id\":\"180054848980.apps.googleusercontent.com\",\"google_client_secret\":\"sdfsd\",\"google_access_token\":\"{\\\"access_token\\\":\\\"ya29.Ci8YA6-sfsd-asdfas\\\",\\\"token_type\\\":\\\"Bearer\\\",\\\"expires_in\\\":3600,\\\"refresh_token\\\":\\\"1\/534ewsdcy\\\",\\\"created\\\":1467867036}\",\"ga_active_web_property\":{\"__PHP_Incomplete_Class_Name\":\"Google_Webproperty\",\"accountId\":\"7489234\",\"childLink\":{\"__PHP_Incomplete_Class_Name\":\"Google_WebpropertyChildLink\",\"href\":\"https:\/\/www.googleapis.com\/analytics\/v3\/management\/accounts\/7489234\/webproperties\/UA-7489234-1\/profiles\",\"type\":\"analytics#profiles\"},\"created\":\"2016-06-28T19:38:17.530Z\",\"id\":\"UA-7489234-1\",\"industryVertical\":\"COMPUTERS_AND_ELECTRONICS\",\"internalWebPropertyId\":\"11922adsf\",\"kind\":\"analytics#webproperty\",\"level\":\""' . '}}';
$strWithoutSlash = str_replace("\\\"",'"',$st);
$array = json_decode($strWithoutSlash,true);

所以可以尝试这个(或者在json_decode之前使用str_replace类似的东西):

 $field = json_decode(str_replace("\\\"",'"',get_post_meta((int)$id[0], $customFieldName, true) . '}}'),true);