将这个字符串(PHP Array)转换为JSON编码字符串的最简单方法是什么?



我的错误日志给我发了一封电子邮件,其中包括一个大数组的数据,这是存储在用户会话。这个数组应该已经转换为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

我能想到的最简单的方法是输出一个简单的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);

相关内容

  • 没有找到相关文章

最新更新