将此字符串(PHP数组)转换为JSON编码字符串的最简单方法是什么?

时间:2016-10-05 15:22:30

标签: php arrays json multidimensional-array

我的错误日志向我发送了一封电子邮件,其中包含大量数据,这些数据存储在用户会话中。这个数组应该已经转换为JSON编码的字符串并存储在我的数据库中,但出了点问题。如果我将数据作为文本字符串,那么转换回JSON并保存回数据库的最快方法是什么。以下是数组中某些数据的示例。请记住:我将此文本字符串作为电子邮件,而不是实际数组。电子邮件中的内容周围有<pre>个标签。

            [customer_firstname] => James
            [customer_lastname] => Smith
            [customer_address1] => 
            [customer_postcode] => AB12CD
            [customer_address2] => 
            [customer_address3] => 
            [customer_address4] => 
            [customer_town] => London
            [customer_county] => 
            [customer_country] => UK

1 个答案:

答案 0 :(得分:1)

我能想到的最简单的方法是在输出上使用简单的str_replace,将其转换为可以复制粘贴到PHP脚本然后转换为JSON的数组。

<?php
  $errorInfo = "[customer_firstname] => James
        [customer_lastname] => Smith
        [customer_address1] => 
        [customer_postcode] => AB12CD
        [customer_address2] => 
        [customer_address3] => 
        [customer_address4] => 
        [customer_town] => London
        [customer_county] => 
        [customer_country] => UK";

  echo str_replace(["[", "]", "=> ", "\n"], ["'", "'", "=>\"", "\",\n<br />"],  $errorInfo);
?>

输出:

'customer_firstname' =>"James", 
'customer_lastname' =>"Smith", 
'customer_address1' =>"", 
'customer_postcode' =>"AB12CD", 
'customer_address2' =>"", 
'customer_address3' =>"", 
'customer_address4' =>"", 
'customer_town' =>"London", 
'customer_county' =>"", 
'customer_country' =>"UK

请注意,错过了最后一个结束语...需要自己添加或在str_replace之后添加

然后添加大括号并指定:

$error = [
  'customer_firstname' =>"James", 
  'customer_lastname' =>"Smith", 
  'customer_address1' =>"", 
  'customer_postcode' =>"AB12CD", 
  'customer_address2' =>"", 
  'customer_address3' =>"", 
  'customer_address4' =>"", 
  'customer_town' =>"London", 
  'customer_county' =>"", 
  'customer_country' =>"UK"];

Simplez:

echo json_encode($error);