【问题标题】:What is the easiest way to convert this string (PHP Array) to a JSON encoded string?将此字符串(PHP 数组)转换为 JSON 编码字符串的最简单方法是什么?
【发布时间】:2017-02-14 03:15:21
【问题描述】:

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

【问题讨论】:

  • @MagnusEriksson 您无法对数组的文本表示进行编码。
  • 我认为这是 PHP print_r 格式?没有特定的方法可以将其转换为任何东西。您也许能够从中获取数据,但该格式没有对特殊字符采取任何预防措施,并且解析起来可能会模棱两可,因此不适合自动处理。
  • @MagnusEriksson 这个问题清楚地表明,目的是对数组 JSON 进行编码,但出了点问题。

标签: php arrays json multidimensional-array


【解决方案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"];

简单:

echo json_encode($error);

【讨论】:

  • 这有点天真,因为它会在[customer_whatever] =&gt; foor"bar 上爆发。数据中任何'"[] 的存在都可能破坏它。
  • @meagar 是的,没错。正则表达式可以解决这个问题,但我不是正则表达式专家,所以我坚持简单。
  • this 这样的东西是理想的……但是,正如您所见,它非常复杂。
猜你喜欢
  • 1970-01-01
  • 2012-01-07
  • 2012-09-16
  • 2010-09-18
  • 1970-01-01
  • 2013-06-23
  • 2021-07-21
  • 2012-08-01
  • 1970-01-01
相关资源
最近更新 更多