【问题标题】:Can someone please explain to me what the "\" inside this php array do?有人可以向我解释一下这个 php 数组中的“\”是做什么的吗?
【发布时间】:2018-08-07 11:57:36
【问题描述】:

在 AJAX 调用中,有以下 php 代码:

$jsonOutput =
                "{
                            id: \"0\",
                            name: \"dauerreservierung\",
                            startDate: new Date('".date("Y-m-d", strtotime('-100 year',
                            $today))."'),
                            endDate: new Date('".date("Y-m-d", strtotime('+20 year',
                            $today))."'),
                            \"color\": \"#FF0000\",
                        }";

我在遵循这种语法时确实遇到了问题。那些斜线在那里做什么?为什么“连接到斜线? 并且:这里是否创建了关联数组?

【问题讨论】:

  • 他们正在转义双引号,因为整个块已经被双引号包围了。
  • 不管你怎么蒙皮,这个json都不是合法的json,所以你的里程肯定会有所不同。

标签: php


【解决方案1】:

这个变量不是一个数组,它是一个包含 JSON 对象的字符串。

在 PHP 中,如果你想在字符串中加上引号,你必须使用 \ 转义它们

例子:

$my_life = 'I\'m eating an apple';
$json = "{\"id\": 1, \"value\": 42}";

你应该尝试echo $jsonOutput;看看发生了什么

【讨论】:

    【解决方案2】:

    反斜杠 (\) 在 PHP 和 JSON 中都是一个特殊字符。两种语言都使用它来转义字符串中的特殊字符,为了在字符串中正确表示反斜杠,您必须在 PHP 和 JSON 中为其添加另一个反斜杠。

    更多细节请参考这个PHP手册http://php.net/manual/en/language.types.string.php#language.types.string.syntax.single

    也可以参考这个StackOverflow link

    【讨论】:

      【解决方案3】:

      如果您在 PHP 中使用此响应,请使用

      json_decode(input_string)
      

      从 json 中获取(反斜杠)

      如果您使用 javascript,请使用

      string.replace(/\\\//g, "/"); or JSON.parse(input_string)
      

      【讨论】:

      • 如果这得到一个 php json_decode,它将失败。
      • 是的,您需要确保在编码和解码 json 时遵循通用模式
      猜你喜欢
      • 1970-01-01
      • 2011-03-19
      • 1970-01-01
      • 2010-12-17
      • 2014-12-06
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多