简体   繁体   English

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

[英]What is the easiest way to convert this string (PHP Array) to a JSON encoded string?

My error log has sent me an email which includes a big array of data, which was stored in the users session. 我的错误日志给我发送了一封电子邮件,其中包含大量数据,这些数据存储在用户会话中。 This array SHOULD have been converted to a JSON encoded string and stored in my database but something has gone wrong. 这个数组应该已经转换成JSON编码的字符串并存储在我的数据库中,但是出了点问题。 If I have the data as a text string, what is the quickest way to convert back to JSON and save back to my database. 如果我将数据作为文本字符串存储,那么转换回JSON并保存回数据库的最快方法是什么。 Here is an example of SOME of the data from the array. 这是来自数组的一些数据示例。 Remember: I have this as a text string an en email, not as an actual array. 切记:我将其作为电子邮件中的文本字符串,而不是实际的数组。 The content in the email has the <pre> tags surrounding it. 电子邮件中的内容周围带有<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

The simplest way I can think of is a simple str_replace on the output, converting it into an array that you can copy-paste into a PHP script and then convert to JSON. 我能想到的最简单的方法是在输出中使用简单的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);
?>

Outputs: 输出:

'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

Note that the last closing quote is missed... Need to add this yourself or add it after the str_replace 请注意,最后一个引号被遗漏了...需要自己添加或在str_replace之后添加

Then add braces and assign: 然后添加括号并分配:

$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: Simplez:

echo json_encode($error);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM